"每个对象都有一个私有属性,该属性保存到另一个称为其原型的对象的链接。该原型对象有自己的原型,依此类推,直到到达一个以 null 作为原型的对象。根据定义,null 没有原型,并作为这个原型链的最后一环。 ”
第一个问题- 我希望“每个对象都包含原型”,作者的意思是“每个函数对象”都包含公共 原型属性,因为这样的对象var myObj = {}
没有任何公共原型。
请参阅下面的 concole 屏幕截图 - 请注意__proto__
使用 {} 创建的对象不存在公共原型属性(而不是 private ) -
第二个问题——我在查一个简单函数的原型链的时候看了上面的文献,一开始好像是无限深的——后来发现原型的构造函数其实是在引用自己。与Mozilla 文档中提到的不同——这里的原型链似乎并没有以null
根结束。
我想这是为了支持基于原型的继承而设计的。但是,如果可以解释一下,原型构造函数中的这种自我引用究竟如何帮助实现这一目标,我将不胜感激?
如果您想查找那里描述的原型链:
Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.
You should look at the __proto__
properties (which will point to the internal prototype of the object being examined).
Here, you see that the internal prototype of myFunctionObj
is Function.prototype
, and going up the next level of __proto__
takes you to Object.prototype
, which has no __proto__
(the end of the prototype chain).
The prototype
property of myFunctionObj
refers to the internal prototype of instantiated objects (like const obj = new myFunctionObj();
, and then obj.__proto__ === myFunctionObj.prototype
), not to the internal prototype of the myFunctionObj
itself.
Only function
s have a .prototype
property, usually, and their .prototype
will refer to the internal prototype of instances created with new
. Plain objects don't have a .prototype
property (because plain objects can't be called to instantiate something), but you can still access the internal prototype of a plain object (or of anything) using Object.getPrototypeOf
(or .__proto__
):
const obj = {};
console.log(
obj.__proto__ === Object.prototype,
Object.getPrototypeOf(obj) === Object.prototype,
);
A function's .prototype.constructor
is indeed just a self-reference back to the function.
function foo(){};
console.log(
foo.prototype.constructor === foo
);
这不是非常有用的,当你已经有了构造参考,但它是当你有一个实例的引用是有用的,但不知道它的构造-与原型继承,访问实例的.constructor
属性会给你使用的功能构建它:
const bar = (() => {
function Bar(){}
const bar = new Bar();
return bar;
})();
// now Bar is out of scope
// but you can still reference it because you have an instance:
const Bar = bar.constructor;
console.log(Bar);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句