为什么 toString() 即使没有任何对象或字符串也能工作

Why does toString() works even without any object or string to call upon

注意到我正在处理的代码库中的一些东西。

如果你只是执行 toString() 而没有任何对象调用它就可以了!

最初我认为这一定是对 window 对象进行隐式调用的结果,但从这个

中看不出来

alert(toString())

alert(window.toString())

两个 return 不同的结果因此必须 运行 在不同的实体上,那么它是如何工作的?

同样的功能:

window.toString === toString  // true

原因是,如果您在 window 上调用,那么 this 就是 window

现在,您可能想知道,如果 toString() 原样是 运行,那么 this 不应该是全局对象,它也是 window ?应该是因为 toString() 的代码在“严格”模式下是 运行ning,这意味着 this 将是 undefined.

在浏览器中试试 Google Chrome:

function foo() { 
  "use strict"; 
  console.log(this);
}

function bar() {  
  console.log(this);
}

foo();
bar();

现在,如果 thisundefined,则 specs:

If the this value is undefined, return "[object Undefined]".