2017-05-28 229 views
0

下面是调试查询和响应的名单,在全球范围内的水平在node.js中执行:Node.js的全球范围

this.toString() 
 
    "[object Object]" 
 
Object.getPrototypeOf(this).toString() 
 
    "[object Object]" 
 
Object.getPrototypeOf(Object.getPrototypeOf(this)) 
 
    null 
 
this.constructor 
 
    function Object() { [native code] } 
 
Object.prototype.toString() 
 
    "[object Object]" 
 
Object.prototype.toString.call(this) 
 
    "[object Object]" 
 

 
Function.prototype.toString() 
 
    "function() {}" 
 
Function.prototype.toString.call(this) 
 
    TypeError: Function.prototype.toString is not generic

第一组的反应表明,全局范围由一个扩展Object.prototype的对象来表示,如同可以预料的那样。所以我期望调用Function.prototype的.toString()这个会失败,就像它的确如此(参见最后一个查询)。我期待在前面的查询通过一个隐含的这个,所以同样失败,但它返回function(){}

为什么不同,以及响应中引用了什么函数?

+0

倒数第二等价于'Function.prototype.toString.call(Function.prototype)'。全局范围内的'this'的值不被它使用。 –

回答

0

在一个函数调用,this势必任一对象,该对象的“函数被调用的”或全局对象,例如:

const obj = { 
    foo() { 
    console.log(this); 
    }, 
}; 

obj.foo(); // this is bound to obj 
const obj2 = {}; 
obj2.bar = obj.foo; 
obj2.bar(); // this is bound to obj2 
const g = obj.foo; 
g(); // this is bound to the global object 

因此,Function.prototype.toString()是完全一样Function.prototype.toString.call(Function.prototype)。这是该函数的实现问题,如果调用函数以外的其他函数,则会抛出该函数。