EN
JavaScript - how to use '.call(...)' method with (or instead) 'new' operator
5 points
In this article we would like to show how to create object with MyClass.call(...)
method instead of new
operator in JavaScript.
Simple solution:
xxxxxxxxxx
1
function MyClass(a, b) {
2
console.log(a + ' ' + b);
3
this.print = function(c, d) {
4
console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
5
};
6
}
7
8
var object = { };
9
MyClass.call(object, 'a', 'b');
10
11
object.print('c', 'd');
Note: read this article to see
MyClass.apply(...)
method examples.
Check below alternative solutions:
There are few different ways how to achieve same effect, what was presenbted in this section.
xxxxxxxxxx
1
function MyClass(a, b) {
2
console.log(a + ' ' + b);
3
this.print = function(c, d) {
4
console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
5
};
6
}
7
8
var object = new (MyClass.bind.call(MyClass, null, 'a', 'b'));
9
object.print('c', 'd');
xxxxxxxxxx
1
function MyClass(a, b) {
2
console.log(a + ' ' + b);
3
this.print = function(c, d) {
4
console.log(a + ' ' + b + ' -> ' + c + ' ' + d);
5
};
6
}
7
8
var object = new (Function.prototype.bind.call(MyClass, null, 'a', 'b'));
9
object.print('c', 'd');