Javascript Function.prototype.call()

buf*_*w76 1 javascript functional-programming

我读了一些文章,它说下面两行正在做同样的事情.

fn.call(thisValue);
Function.prototype.call.call(fn, thisValue);
Run Code Online (Sandbox Code Playgroud)

对于1号线,我的理解是,在Javascript中的每个函数对象也有方法call从继承的Function.prototype,哪些call不为法具有this的功能定义中的关键字fnthisValue(我在调用方法传递的第一个参数.fn是函数所以我正在做的fn.call(thisValue)只是调用fn并设置this函数内的关键字thisValue.

但对于第2行,我不明白.有人可以帮助解释它是第2行正在做什么.

Ber*_*rgi 6

让我们从这个设置开始:

function fn() { console.log(this); }
var thisvalue = {fn: fn};
Run Code Online (Sandbox Code Playgroud)

现在你肯定明白这thisvalue.fn()是一个方法调用,并将记录的this值设置为thisvalue对象.

接下来,您似乎知道fn.call(thisvalue)完全相同的调用.或者,我们可以写(thisvalue.fn).call(thisvalue)(仅用于结构的括号,可以省略)thisvalue.fn === fn:

thisvalue.fn(…); // is equivalent to
(thisvalue.fn).call(thisvalue, …); // or:
(fn).call(thisvalue, …);
Run Code Online (Sandbox Code Playgroud)

OK,但fn.call(…)仅仅是一个方法调用,以及-该call方法的函数被调用的fn函数.
它可以作为这样的访问,因为所有的函数对象继承了这个.call从属性Function.prototype-它不是自己的财产一样.fn的上thisvalue对象.但是,fn.call === Function.prototype.call是一样的thisvalue.fn === fn.

现在,我们可以使用以下方法重写该方法调用.call作为显式调用.call():

fn.call(thisvalue); // is equivalent to
(fn.call).call(fn, thisvalue); // or:
(Function.protoype.call).call(fn, thisvalue);
Run Code Online (Sandbox Code Playgroud)

我希望你能发现这种模式,现在可以解释为什么以下工作:

Function.prototype.call.call.call(Function.prototype.call, fn, thisvalue);
var call = Function.prototype.call; call.call(call, fn, thisvalue);
Run Code Online (Sandbox Code Playgroud)

打破这一点是留给读者的练习:-)