In JavaScript, constructing an object instance using the 'new' operator is commonly done by directly passing arguments to the constructor. However, there are scenarios where one might desire to provide arguments dynamically. This article addresses the question of whether using '.apply()' with the 'new' operator to accomplish this is feasible.
Despite its versatility, the '.apply()' method cannot be directly employed with the 'new' operator. Attempts to do so will result in unexpected behavior or errors.
Recognizing the need for such functionality, various innovative solutions have been proposed by the JavaScript community.
One approach, credited to Matthew Crumley, utilizes a function prototype to create a workaround:
var createSomething = (function() { function F(args) { return Something.apply(this, args); } F.prototype = Something.prototype; return function() { return new F(arguments); } })();
This solution effectively creates a new function with the desired behavior.
ECMAScript 5's 'Function.prototype.bind' offers a cleaner solution:
function newCall(Cls) { return new (Function.prototype.bind.apply(Cls, arguments)); }
This method seamlessly integrates with the 'new' operator and can be applied to all types of constructors, including those with special behavior like 'Date'.
While discouraged due to potential security concerns, the 'eval' method provides another workaround:
var s = eval("new Something(" + [a, b, c] + ")");
These solutions harness the bind() method to create a function that accepts the desired arguments. Then, the 'new' operator is used to instantiate an object from that function.
Creating objects with variable arguments using '.apply()' and the 'new' operator requires some ingenuity. By leveraging the available JavaScript features, developers can implement these techniques to achieve their desired functionality.
The above is the detailed content of Can You Use `.apply()` with the `new` Operator in JavaScript to Create Objects with Variable Arguments?. For more information, please follow other related articles on the PHP Chinese website!