当你这样做时obj.f()
, this
函数内部f
将参考obj
.
在第一个例子中,deentify()
在字符串上调用。在该函数中,他只需要调用该函数的对象,即字符串,这就是this
在 - 的里面deentify()
函数将要引用。
为什么我们需要that
The add1
函数需要存储对原始函数的引用add
以某种方式发挥作用。add1
不能用this
, 因为它是not称为add.add1
。这是通过创建一个闭包来克服的that
,他在其中保存对您执行的函数的引用curry()
on (add()
在示例中)。
你打电话时add.curry()
, this
将参考add
功能。 (因为你打电话给curry()
on add
)。由于柯里函数内部的闭包,that
将保留其值并仍将引用add
函数时add1()
叫做。
If this
在返回的函数内部使用curry()
,它会指的是window
object.
Function.method('curry', function() {
var args = arguments,
that = this; //reference to add
return function () {
//`apply` calls add
return that.apply(null, args.concat(arguments));
};
});
var add1 = add.curry(1);
document.writeln(add1(6));
Note: 重要的是要看到,第一个return
第一个片段中表示the deentify()
函数,而第一个return
第二个片段中的表示返回值of the curry()
功能。
如果你想了解arguments
/apply()
让咖喱发挥作用的魔法,只需在评论中询问,我很乐意详细说明。