在 JavaScript 中,当我们实例化派生对象时,原型的函数隐藏在哪里

In JavaScript, where do prototype's functions hide when we instantiate the derived object?

本文关键字:原型 函数 隐藏 对象 在哪里 派生 JavaScript 我们 实例化      更新时间:2023-09-26

我目前正在尝试弄清楚原型继承在JavaScript中是如何工作的。这是我目前试图解开的谜团。

假设我们设置了以下结构:

var base = { greet : "hello" }
var child = function () {}
child.prototype = base;
child.prototype.protoSomething = function () {}
var instance = new child();

没什么好看的。现在让我们看看instance属性(自己的或其他)有什么:

for(prop in instance) {
    console.log(prop); // prints 'greet', 'protoSomething'
}

好吧,所以它有greetprotoSomething,他们是instance自己的成员吗?

for(prop in instance) {
    if(instance.hasOwnProperty(prop))
        console.log(prop); // nothing is printed
}

不,自己的属性列表是空的。它们在instance的原型中吗?

if(instance.prototype === undefined) {
    console.log("'instance' has no prototype"); // gets printed
}

好吧,无赖,instance没有分配原型。那么,如果属性不是拥有的,也没有原型,它们从何而来?我觉得在这一点上某种图表会非常好。

只有函数具有属性prototype

instance.constructor.prototype === base // return true

若要获取对象的原型,应使用 Object.getPrototypeOf 方法。

Object.getPrototypeOf(instance) === base // return true

此页面应该可以帮助您:

http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

简而言之,实例的"幕后"原型(通过new创建)无法以任何方式访问,因此它返回undefined。只有构造函数(已在其上手动设置 .prototype 属性)在尝试检索时返回任何内容。