10 09/2014

javascript function apply 和 call

最后更新: Wed Sep 10 2014 12:37:50 GMT+0800

Function.prototype.call 和 Function.prototype.apply 几乎一样,区别在于 call 参数是 参数列表(逗号分隔);apply 参数是 数组。

function foo(name, prof) {
    console.log("俺叫 " + name + " 俺是" + prof);
}
foo("guoshuang", "前端");
foo.apply(this, ["guoshuang", "前端"]);
foo.call(this, "guoshuang", "前端");

While the syntax of this function( Function.prototype.call ) is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

第一个参数指向该方法的宿主对象

默认是 this,一般情况下就是 window 对象;在 a 对象执行 foo 方法

foo.apply(a, [1,2]);
foo.call(a, 1, 2);