2013-05-29 63 views
2

爲什麼我會收到my_game.size()返回的大小1?我認爲make_game的參數會插入game,所以arguments.length會是3,但顯然不是。這是什麼原因?爲什麼我的參數數組只有1的大小?

function game() 
{ 
    var args = arguments; 
    this.size = function() { return args.length; }; 
} 

function make_game() 
{ 
    return new game(arguments); 
} 

var my_game = make_game(4, 'a', true); 

console.log(my_game.size()); // 1 

回答

6

你傳入整個arguments對象作爲單個參數

如果你想在它傳遞的每個參數作爲一個單獨的參數那麼你必須明確地這樣做:

return new game(arguments[0], arguments[1], arguments[2]); 

如果你沒有使用一個構造函數,那麼你可以使用apply method

return game.apply(this, arguments); 

...但因爲你是你會得到這樣的結果:因爲它試圖利用apply的構造函數,而不是game

Uncaught TypeError: function apply() { [native code] } is not a constructor 

...。

1

你只傳遞一個參數給你的構造函數,它是arguments

變化

var args = arguments; 

var args = arguments[0]; 
3
return new game(arguments); 

您正在傳遞參數對象,只是一個對象。所以這是一個論點。

要轉發參數正常功能,你可以使用應用:

var fn = function() { 
    otherFn.apply(null, arguments); 
}; 

但這2周的事情,它傳遞的參數數組作爲參數使用,但它也將執行上下文(價值的this)。但是構造函數創建它自己的值。這就提出了一個問題...


轉發參數構造函數是純JS太多麻煩。在咖啡腳本中,這很容易,但它編譯成一些瘋狂的JS。 See here

技巧似乎是用無操作構造函數創建一個新的子類,並手動調用構造函數。

var newConstructor = function() {}; // no-op constructor 
newConstructor.prototype = Game.prototype; // inherit from Game 
var child = new newConstructor(); // instantiate no-op constructor 
var result = Game.apply(child, arguments); // invoke real constructor. 

但是,這是相當毛。也許你應該重新考慮你的方法。

4

當你game(arguments)裏面的make_game()您正在使用一個參數,它是傳遞給make_game()該參數數組調用game()

如果要單獨通過每個參數,你通常會使用game.apply(arguments),但得到這個與new正常工作以及它變得有點複雜:

function make_game() 
{ 
    return new (Function.prototype.bind.apply(game, arguments)); 
} 

This answer有怎樣的詳細解釋此方法有效。

+0

哇,這很有趣,而且比我的解決方案簡單得多。它的工作原理是因爲'bind'只爲正確的調用返回一個函數全部設置。很光滑。 –

0

僅僅因爲你只傳遞一個參數。

function game() 
{ 
    var args = arguments; 
    this.size = function() { return args.length; }; 
} 

function make_game() 
{ 
    return new game(arguments); // passing only one 
} 

function make_game2() 
{ 
    return new game(arguments[0], arguments[1], arguments[2]); // passing three 
} 

var my_game = make_game(4, 'a', true); 

console.log(my_game.size()); // 1 


var my_game2 = make_game2(4, 'a', true); 

console.log(my_game2.size()); // 3 

你可以使用另一個函數初始化對象

function game() 
{ 
    var args; 
    this.size = function() { return args.length; }; 
    this.init = function(){ 
     args = arguments; 
    } 
} 

function make_game() 
{ 
    var gm = new game(); 
    gm.init.apply(gm, arguments); 
    return gm; 
} 


var my_game = make_game(4, 'a', true); 

console.log(my_game.size()); // 3 

這是展示它是如何工作的。強烈建議遵循基於原型的設計。

相關問題