在‘new’操作符中使用.application()。這個是可能的嗎?在JavaScript中,我希望創建一個對象實例(通過new運算符),但是將任意數量的參數傳遞給構造函數。這個是可能的嗎?我想做的是這樣的事情(但下面的代碼不起作用):function Something(){
// init stuff}function createSomething(){
return new Something.apply(null, arguments);}var s = createSomething(a,b,c); // 's' is an instance of Something答案從這里的回復中可以清楚地看出,這里沒有內置的呼叫方式。.apply()帶著new接線員。然而,人們提出了一些真正有趣的解決方案。我更喜歡的解決辦法是這張是馬修·克魯姆利寫的(我修改了它以通過arguments財產):var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}})();
在‘new’操作符中使用.application()。這個是可能的嗎?
一只名叫tom的貓
2019-06-13 19:21:48