简体   繁体   English

Node.js全球范围

[英]Node.js Global Scope

Below is list of debugger queries, and responses, executed in a node.js at the global scope level: 以下是在全局范围级别的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 

The first set of responses suggests that the global scope is represented by an object that extends Object.prototype, as might be expected. 第一组响应表明,正如预期的那样,全局范围由扩展Object.prototype的对象表示。 So I'd expect that calling Function.prototype's .toString() on this would fail, as indeed it does (see the last query). 所以我希望,在这个调用Function.prototype的的的ToString()将失败,因为的确如此(见的最后一个查询)。 I was expecting the query preceding that to pass an implicit this and so fail likewise, but it returns function () {} . 我期望在此之前的查询传递一个隐式this ,因此同样失败,但是它返回function(){}

Why the difference, and what function is being referenced in the response? 为什么会有所不同,以及响应中引用了什么功能?

In a function call, this is bound to either the object that "the function was called on" or the global object, for example: 在函数调用中, 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

Therefore, Function.prototype.toString() is exactly the same as Function.prototype.toString.call(Function.prototype) . 因此, Function.prototype.toString()Function.prototype.toString.call(Function.prototype)完全相同。 That's the matter of implementation of this function that it throws if called on anything other than a Function. 这是该函数的实现的问题,如果在Function以外的任何其他函数上调用它,它将引发该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM