EN
JavaScript - how to use '.apply(...)' method with (or instead) 'new' operator
4 points
In this article we would like to show how to create object with MyClass.apply(...)
method instead of new
operator in JavaScript.
Simple solution for modern JavaScript:
xxxxxxxxxx
1
const parameters = ['a', 'b'];
2
const object = new MyClass(parameters);
Simple solution for older JavaScript:
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.apply(object, ['a', 'b']);
10
11
object.print('c', 'd');
Note: read this article to see
MyClass.call(...)
method examples.
Check below alternative solutions:
There are few different ways how to achieve same effect, what was presenbted in this section.
In modern JavaScript, the following approach is mostly correct.
xxxxxxxxxx
1
class MyClass {
2
constructor(a, b) {
3
this.a = a;
4
this.b = b;
5
console.log(a + ' ' + b);
6
}
7
print(c, d) {
8
console.log(this.a + ' ' + this.b + ' -> ' + c + ' ' + d);
9
}
10
}
11
12
const parameters = ['a', 'b'];
13
const object = new MyClass(parameters);
14
15
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 (MyClass.bind.apply(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.apply(MyClass, [null, 'a', 'b']));
9
object.print('c', 'd');