gpt4 book ai didi

javascript - 为什么原型(prototype)的构造函数会引用自身?

转载 作者:行者123 更新时间:2023-11-29 18:40:52 25 4
gpt4 key购买 nike

来自 Mozilla-javascript-docs

每个对象都有一个私有(private)属性,该属性包含指向另一个称为其原型(prototype)的对象的链接。该原型(prototype)对象有自己的原型(prototype),依此类推,直到到达以 null 作为其原型(prototype)的对象。根据定义, null 没有原型(prototype),作为这个原型(prototype)链的最后一环。"

第一个问题 - 我希望“每个对象都包含原型(prototype)”,作者的意思是“每个函数对象”都包含公共(public) < strong>prototype 属性,因为像这样的对象 var myObj = {} 没有任何 public 原型(prototype)。

请查看下面的控制台屏幕截图 - 注意公共(public)原型(prototype)属性(而不是私有(private) __proto__)对于使用 {} 创建的对象不存在 - enter image description here

第二个问题 - 在查看一个简单函数的原型(prototype)链时,看了上面的文献,一开始好像是无限深的 - 但后来我意识到prototype 实际上是指回自身。不像Mozilla's documentation中提到的那样- 这里的原型(prototype)链似乎没有以 null 作为根结束。

我想这是为了支持基于原型(prototype)的继承而设计的。但如果可以解释一下,我将不胜感激,原型(prototype)构造函数中的这种自引用究竟如何帮助实现这一目标

enter image description here

最佳答案

如果你想查找那里描述的原型(prototype)链:

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.

您应该查看 __proto__ 属性(它将指向被检查对象的内部原型(prototype))。

enter image description here

在这里,您会看到 myFunctionObj 的内部原型(prototype)是 Function.prototype,而往下一层 __proto__ 会带您到Object.prototype,其中没有__proto__(原型(prototype)链的末尾)。

myFunctionObjprototype 属性指的是实例化对象 的内部原型(prototype)(如const obj = new myFunctionObj(); ,然后是 obj.__proto__ === myFunctionObj.prototype),而不是 myFunctionObj 本身的内部原型(prototype)。

只有 function.prototype 属性,通常,它们的 .prototype 将引用内部原型(prototype) 个使用 new 创建的实例。普通对象没有 .prototype 属性(因为不能调用普通对象来实例化某些东西),但您仍然可以使用 Object.getPrototypeOf(或.__proto__):

const obj = {};
console.log(
obj.__proto__ === Object.prototype,
Object.getPrototypeOf(obj) === Object.prototype,
);

函数的 .prototype.constructor 实际上只是对函数的 self 引用。

function foo(){};
console.log(
foo.prototype.constructor === foo
);

当您已经拥有对构造函数的引用时它不是很有用,但是当您拥有对实例的引用但不知道其构造函数时它很有用 - 具有原型(prototype)继承,访问该实例的 .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);

关于javascript - 为什么原型(prototype)的构造函数会引用自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com