JavaScript 的 *this* 关键字从 string.prototype 中指向窗口

标签 javascript prototype this

好吧,这可能会让我赢得“今日头条”徽章。

为什么this在下面的代码中指向window

if (!String.prototype.Trim)
{
    String.prototype.Trim = function()
    {
        var result = this.replace(/^\s+|\s+$/g, "");
        return result;
    };
}

据我了解,this 的计算结果应该是当前字符串实例的值。相反,它正在评估当前的窗口对象。因此,以下操作惨遭失败:

var baz = 'foo bar      '.Trim();

请注意,此代码已经使用了很长一段时间,并且是基于我在 intartoobs 上看到的到处都是广告的代码。所以这种模式似乎是推荐的做法。我不明白为什么 this 没有指向我认为它应该指向的数据。 (在 Visual Studio 中,当我将鼠标悬停在它上面或在“监视”窗口中查看它时,它显示为 [object window])。

(IE 8 [32 位];Win7;纯 ole HTML 页面。)

最佳答案

In Visual Studio, when I hover over it, or view it in the Watches window, it shows up as [object window]

听起来像是 VS 中的范围解析错误。这不可能是 IE 中的错误,否则成千上万的原型(prototype)函数会被破坏。

关于JavaScript 的 *this* 关键字从 string.prototype 中指向窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5517497/

相关文章:

c++ - 为什么 'this' 是指针而不是引用?

javascript - "new"这个词将函数更改为对象?

javascript - 为什么 jquery 中的 focus() 不起作用?

javascript - 容器对象的引用相等

javascript - 标签文本框服务器控件

javascript - VueJS : v-for with dynamic component strange behavior

javascript - JS 继承和变异原型(prototype)

JavaScript:使用 Object.create 时获得的最大优势是什么

javascript - JS defineProperty 和原型(prototype)

Node.js - 变量范围和垃圾收集