Languages
[Edit]
EN

JavaScript - how to use '.call(...)' method with (or instead) 'new' operator

5 points
Created by:
JustMike
3593

In this article we would like to show how to create object with MyClass.call(...) method instead of new operator in JavaScript.

Simple solution:

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = { };
MyClass.call(object, 'a', 'b');

object.print('c', 'd');

Note: read this article to see MyClass.apply(...) method examples.

Check below alternative solutions:

Alternative solutions

There are few different ways how to achieve same effect, what was presenbted in this section.

new operator with .bind.call(...) methods example

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = new (MyClass.bind.call(MyClass, null, 'a', 'b'));
object.print('c', 'd');

new operator, .bind.call(...) methods with Function class example

// ONLINE-RUNNER:browser;

function MyClass(a, b) {
	console.log(a + ' ' + b);
	this.print = function(c, d) {
		console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
	};
}

var object = new (Function.prototype.bind.call(MyClass, null, 'a', 'b'));
object.print('c', 'd');
Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join