JavaScript 的 *this* 关键字从 string.prototype 中指向窗口
好吧,这可能会让我获得“每日猛击”徽章。
为什么下面代码中的 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 页面。)
Okay, this will probably earn me the Headslam of the Day badge.
Why is this
pointing at window
in the following code?
if (!String.prototype.Trim)
{
String.prototype.Trim = function()
{
var result = this.replace(/^\s+|\s+$/g, "");
return result;
};
}
As I understand it, this
should evaluate to the value of the current string instance. Instead, it's evaluating to the current window object. Thus, the following fails miserably:
var baz = 'foo bar '.Trim();
Note that this code has been used for quite some time, and is based on code I see advertised all over the place on the intartoobs. So this pattern seems to be the recommended way of doing this. I can't figure out why this
isn't pointing to the data I think it should be pointing at. (In Visual Studio, when I hover over it, or view it in the Watches window, it shows up as [object window]
).
(IE 8 [32-bit]; Win7; plain-ole HTML page.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来像是 VS 中的范围解析错误。这不可能是 IE 中的错误,否则数以千计的原型函数将被破坏。
Sounds like a scope resolution bug in VS. There's no way this can be a bug in IE or else thousands of prototypal functions would break.
我最近遇到了这个问题,发现原因是 JS 捆绑器破坏了我的代码。我能够通过将修改
String.prototype
的代码包含在匿名函数中然后调用它来修复它。所以
我必须写:
I ran into this problem recently and found the cause was the JS bundler mangling my code. I was able to fix it by enclosing code modifying
String.prototype
in an anonymous function and then calling it.So instead of:
I had to write:
当函数名称后面的括号丢失时,我遇到了这个问题,例如
Error
Fix
I faced this issue when the parentheses after function name were missing, for example
Error
Fix