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:
const parameters = ['a', 'b'];
const object = new MyClass(...parameters);
Simple solution for older JavaScript:
// 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.apply(object, ['a', 'b']);
object.print('c', 'd');
Note: read this article to see
MyClass.call(...)
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 spread syntax (...
) example
In modern JavaScript, the following approach is mostly correct.
// ONLINE-RUNNER:browser;
class MyClass {
constructor(a, b) {
this.a = a;
this.b = b;
console.log(a + ' ' + b);
}
print(c, d) {
console.log(this.a + ' ' + this.b + ' -> ' + c + ' ' + d);
}
}
const parameters = ['a', 'b'];
const object = new MyClass(...parameters);
object.print('c', 'd');
new
operator with .bind.apply(...)
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.apply(MyClass, [null, 'a', 'b']));
object.print('c', 'd');
new
operator, .bind.apply(...)
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.apply(MyClass, [null, 'a', 'b']));
object.print('c', 'd');