好吧,这可能会让我赢得“今日头条”徽章。
为什么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/