一个String.prototype的“this”不返回字符串? [英] a String.prototype's "this" doesn't return a string?

查看:91
本文介绍了一个String.prototype的“this”不返回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里发生了什么?就在我认为我内部和外部都知道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

http://jsfiddle.net/dJBmf/

这打破了一些期望字符串的东西,比如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:


  1. 如果函数代码是严格代码,请将ThisBinding设置为
    thisValue。

  2. 否则,如果thisValue为null或未定义,则设置ThisBinding到
    全局对象。

  3. 否则如果Type(thisValue)不是Object,则将ThisBinding设置为
    ToObject(thisValue)。

  4. 另外将ThisBinding设置为thisValue

  1. If the function code is strict code, set the ThisBinding to thisValue.
  2. Else if thisValue is null or undefined, set the ThisBinding to the global object.
  3. Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆