这些示例中“this”的调用有什么区别?

2023-12-12

我正在读克罗克福德的《JS:好部分》。他有两个使用这个的例子,我不明白为什么在一个例子中他使用this在另一个他使用that.

第一个例子:

String.method('deentify', function() {
    var entity = {
        quot:   '"',
        lt:     '<',
        gt:     '<'
    };

    return function() {
        return this.replace(/&([^&;]+);/g,
            function (a, b) {
                var r = entity[b];
                return typeof r === 'string' ? r : a;
            }
        );
    };
}());
document.writeln('&lt;&quot;&gt;'.deentify()); 

第二个例子:

Function.method('curry', function() {
    var args = arguments, that = this;
    return function () {
        return that.apply(null, args.concat(arguments));
    };
});
var add1 = add.curry(1);
document.writeln(add1(6));

为什么第一个例子可以访问this直接地?该示例与其后面的示例有什么区别?


当你这样做时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()让咖喱发挥作用的魔法,只需在评论中询问,我很乐意详细说明。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这些示例中“this”的调用有什么区别? 的相关文章

随机推荐