为什么将字符串作为"this"传递会导致这种奇怪?

jep*_*jep 7 javascript

我试图理解为什么javascript正在做一些意想不到的事情(对我而言).这里有一些纯粹的代码.换句话说,我实际上并不想扩展String(我实际上是绑定到函数和东西).所以这是没有库的普通javascript.

var s = 'blah';

String.prototype.foo = function () {
  console.log('this === s:', this === s);
  console.log('this == s:', this == s);
  console.log('typeof this:', typeof this);
  console.log('typeof s:', typeof s);
  console.log('this:', this);
  console.log('s:', s);
};

s.foo()
Run Code Online (Sandbox Code Playgroud)

这是Safari脚本控制台中的输出:

this === s: false
this == s: true
typeof this: object
typeof s: string
this: [object Object]
s: blah
Run Code Online (Sandbox Code Playgroud)

IE,FF,Chrome等的输出相似

我试图绕过为什么这个=== s不是真的.为什么这是一个"对象",但s是一个"字符串".

这里发生了什么?

use*_*716 10

"这也是为什么这是一个"对象",但s是一个"字符串"."

如果我们从这个开始,它会更容易.

这是因为当你在原始值上调用一个方法时,它会被转换为它的对象包装器(因为那是方法所在的位置).这意味着this函数中的值将是对象包装器,而不是原始字符串.

就像你这样做:

new String( s ).foo();
Run Code Online (Sandbox Code Playgroud)

所以这解释了typeof结果和[object Object]输出.


"我试图解决为什么这个= = s不是真的."

现在这可能更容易理解了.因为this它不是对原始字符串的引用,而是它的对象包装器,所以您不会通过任何定义来比较相同的项===.

原因==在于它确实类型强制.Object包装器将转换为字符串原语,因此您最终会得到相同的比较.


您应该注意,如果您在严格模式下运行代码,并且在基元上调用该方法,则值this将是原语而不是其对象包装器.