String.prototype的"this"不返回字符串?

ada*_*Lev 28 javascript

这里发生了什么?正当我认为我内外都知道JS时,这个宝石出现了.

String.prototype.doNothing = function() {
  return this;
};

alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo')             // string
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/dJBmf/

这打破了一些期望字符串的东西,比如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将作为字符串对象而不是实际字符串返回.

  • 这就是诀窍,谢谢.你能详细说明或链接到解释这种行为的东西吗? (8认同)
  • 为什么不直接返回`.valueOf()`字符串?:) (2认同)

Bob*_*Bob 25

这里有一个全面概述了的this关键字.基本上,JavaScript将其转换为对象,如果不是一个对象.

当控件进入函数对象F中包含的函数代码的执行上下文,调用者提供thisValue,以及调用者提供的argumentsList时,执行以下步骤:

  1. 如果函数代码是严格代码,请将ThisBinding设置为thisValue.
  2. 否则,如果thisValue为null或未定义,则将ThisBinding设置为全局对象.
  3. 否则,如果Type(thisValue)不是Object,则将ThisBinding设置为ToObject(thisValue).
  4. 否则将ThisBinding设置为thisValue

Numbers和Booleans也是如此.类似的DoNothing函数将返回一种对象.


eve*_*Guy 5

strict模式下运行代码以获得预期结果!