这里发生了什么?正当我认为我内外都知道JS时,这个宝石出现了.
String.prototype.doNothing = function() {
return this;
};
alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo') // string
Run Code Online (Sandbox Code Playgroud)
这打破了一些期望字符串的东西,比如jQuery的.text(str)方法.
McH*_*bie 36
要确保您始终获取字符串,请尝试使用以下代码:
String.prototype.doNothing = function() {
return this.toString();
};
alert(typeof 'foo'.doNothing())
alert(typeof 'foo')
Run Code Online (Sandbox Code Playgroud)
在原始代码中,this将作为字符串对象而不是实际字符串返回.
Bob*_*Bob 25
这里有一个全面概述了的this关键字.基本上,JavaScript将其转换为对象,如果不是一个对象.
当控件进入函数对象F中包含的函数代码的执行上下文,调用者提供thisValue,以及调用者提供的argumentsList时,执行以下步骤:
- 如果函数代码是严格代码,请将ThisBinding设置为thisValue.
- 否则,如果thisValue为null或未定义,则将ThisBinding设置为全局对象.
- 否则,如果Type(thisValue)不是Object,则将ThisBinding设置为ToObject(thisValue).
- 否则将ThisBinding设置为thisValue
Numbers和Booleans也是如此.类似的DoNothing函数将返回一种对象.
| 归档时间: |
|
| 查看次数: |
16226 次 |
| 最近记录: |