为什么我的大小为1 my_game.size()?我认为make_game将插入的参数将被插入game,因此arguments.length将是3,但显然它不是.这是什么原因?
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
Run Code Online (Sandbox Code Playgroud)
您将整个arguments对象作为单个参数传递
如果要将其中的每个参数作为单独的参数传递,则必须明确地这样做:
return new game(arguments[0], arguments[1], arguments[2]);
Run Code Online (Sandbox Code Playgroud)
如果您没有使用构造函数,则可以使用apply方法.
return game.apply(this, arguments);
Run Code Online (Sandbox Code Playgroud)
...但既然你是你会得到这个结果:
Uncaught TypeError: function apply() { [native code] } is not a constructor
Run Code Online (Sandbox Code Playgroud)
...因为它试图apply用作构造函数而不是game.
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |