简体   繁体   English

MDN构造函数属性说明混乱

[英]MDN constructor property explanation confusion

I'm reading this article about constructor property and it states the following: 我正在阅读有关constructor属性的文章 ,并指出以下内容:

Returns a reference to the Object function that created the instance's prototype. 返回对创建实例原型的Object函数的引用。

And they give an example: 他们举了一个例子:

function Tree(name) {
  this.name = name;
}

var theTree = new Tree('Redwood');
console.log('theTree.constructor is ' + theTree.constructor);

Here the instance is theTree and its prototype is Object.getPrototypeOf(theTree) , which is Object function, not Tree . 这里的实例是theTree ,其原型是Object.getPrototypeOf(theTree) ,它是Object函数,而不是Tree What am I misunderstanding? 我有什么误会?

The prototype of an object is typically inherited from its constructor function: 对象的原型通常是从​​其构造函数继承的:

function Tree() {}
Tree.prototype.foo = function () {};

var theTree = new Tree();

theTree now has theTree.foo from its prototype chain . theTree现在具有其原型链中的 theTree.foo The function Tree initialised the object, and is also responsible for the contents of its prototype chain. function Tree初始化该对象,并且还负责其原型链的内容。 That's why they express it as "the Object function that created the instance's prototype" . 这就是为什么他们将其表示为“创建实例原型的Object函数”的原因

Object.getPrototypeOf(theTree) is the prototype of your Tree function Object.getPrototypeOf(theTree)是Tree函数的原型

Object.getPrototypeOf(theTree) == Tree.prototype; // true

Both refer the same object 两者都引用同一个对象

And Tree.prototype has the property named 'constructor' which is infact a reference to the Tree function only 并且Tree.prototype具有名为“ constructor”的属性,实际上仅是对Tree函数的引用

theTree.contructor == Tree.prototype.constructor ;// true

Basically theTree has a proto link (____proto____) and this proto link points to the Tree.prototype. 基本上,Tree有一个proto链接(____proto____),并且此proto链接指向Tree.prototype。 So when you do theTree.constructor it actually follows the proto link and reaches Tree.prototype and finds the constructor which itself it Tree function 因此,当您执行Tree.constructor时,它实际上跟随proto链接并到达Tree.prototype并找到本身就是Tree函数的构造函数

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

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