In JavaScript, it may be desirable to create an object instance using the new operator while passing a variable number of arguments to the constructor. However, this is not achievable using the code snippet you provided.
1. Matthew Crumley's Approach:
This solution involves creating a new function, F, that extends the Something prototype and provides a wrapper for the apply() method. It can be implemented as follows:
2. ECMAScript 5 Solution:
With ECMAScript 5, the Function.prototype.bind method can be employed for a more concise solution:
This function can be utilized as follows:
or even directly:
Explanation:
The bind method allows us to create a new function that has the same context (this value) as the original function but takes a limited number of arguments. By using the apply() method, we can pass a variable number of arguments to the bound function. Finally, the new operator can be applied to the bound function to create a new object instance.
The above is the detailed content of Can You Use the `new` Operator with `.apply()` in JavaScript to Create Objects with Variable Arguments?. For more information, please follow other related articles on the PHP Chinese website!