javascript - 关于JavaScript中 "this"保留字的问题

标签 javascript this

我对 JavaScript 中的 this 保留字有疑问。

检查下面的代码:

Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
    }        
};

String.method('deentityify', function () {

    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };

    return function () {

        /*if (this === String.prototype) {
            alert('true');
        } else {
            alert('false');
        }*/

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

document.write('&lt;&quot;&gt;'.deentityify());

您可以在以下位置编辑以上代码:http://jsfiddle.net/G3Tkm/

我的问题是:

第27行的this保留字是什么return this.replace(/&([^&;]+);/g,是什么?

我猜:this === String.prototype,但事实并非如此。

'<">'的类型是string,this的类型是object。所以 this !== '<">'

非常感谢!

最佳答案

每当我在 JavaScript 代码中找到 this 关键字时,我通常只是向上看,直到找到它所在的周围函数。

然后我尝试了解如何从外部 调用此函数。这很重要,因为 this 的值会根据函数的调用方式而变化。

从您的代码看来,String.method() 的工作是将方法添加到 String 对象的原型(prototype)链中。这是你不应该真正做的事情,它是一种糟糕的 JavaScript 行为,可能会在以后导致一些问题。

但是,为了便于解释,每当您在字符串上调用 deentityify 方法时,例如 "foo".deentityify() - 假设这调用了 whatever你在 String.method('deentityify', function () { 中赋值 - this 实际上成为另一个函数本身(如果 String.method 有效如我所想)。

因此,当使用 "foo".deentityify()() 时,您的 this 将引用调用者,即 "foo".deentityify() "foo".deentityify() 的调用者实际上是 "foo" 本身。

所以基本上 this,在您的例子中,指的是您从中调用方法的 String 对象。

关于javascript - 关于JavaScript中 "this"保留字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4601978/

相关文章:

C++ 类更改 "*this"所指的内容

java - 在 Java : 中迭代 "this"

php - 如何在 PHP header() 之前发送 header ?

javascript - 只有 Javascript 中 for 循环中的最后一次运行有效

javascript - 在每个循环完成渲染集合中的项目后执行代码

javascript - 如何在回调中访问正确的“this”?

javascript - react - 类型错误 : Cannot read property 'props' of undefined

javascript - 购物车挑战 JavaScript 逻辑。有不止一种方法可以解决吗?

javascript - 在 showMessage() 之后添加延迟

javascript - 轮播内幻灯片的延迟加载内容(内容是 oEmbeds/iframes)