一个String.prototype的“this”不返回字符串? [英] a String.prototype's "this" doesn't return a string?
问题描述
这里发生了什么?就在我认为我内部和外部都知道JS的时候,这个宝石出现了。
What is going on here? Just when I thought I knew JS inside and out, this gem comes up.
String.prototype.doNothing = function() {
return this;
};
alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo') // string
这打破了一些期望字符串的东西,比如jQuery的 .text(str)
方法。
This is breaking some things that expect a string, such as jQuery's .text(str)
method.
推荐答案
这是这个
关键字的全面概述。基本上,JavaScript将它转换为一个对象,如果它不是一个。
Here's a thorough overview of the this
keyword. Basically, JavaScript converts it into an object, if it wasn't one.
当
控件进入时执行以下步骤
函数对象F中包含的函数代码的执行上下文
,调用者提供
thisValue,调用者提供
argumentsList:
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisValue, and a caller provided argumentsList:
- 如果函数代码是严格代码,请将ThisBinding设置为
thisValue。 - 否则,如果thisValue为null或未定义,则设置ThisBinding到
全局对象。 - 否则如果Type(thisValue)不是Object,则将ThisBinding设置为
ToObject(thisValue)。 - 另外将ThisBinding设置为thisValue
- If the function code is strict code, set the ThisBinding to thisValue.
- Else if thisValue is null or undefined, set the ThisBinding to the global object.
- Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
- Else set the ThisBinding to thisValue
相同数字和布尔人的事情发生了。类似的 DoNothing
函数会返回一种对象。
Same thing happens to Numbers and Booleans. A similar DoNothing
function would return a type of object.
这篇关于一个String.prototype的“this”不返回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!