gpt4 book ai didi

javascript - 为什么我需要为扩展函数设置构造函数?

转载 作者:行者123 更新时间:2023-11-29 10:20:57 24 4
gpt4 key购买 nike

我试图完全理解“扩展”在 javascript 中的工作原理。

这是我在 google 上找到的一个简单的扩展函数

function extend(child, parent) {

var f = function() {}
f.prototype = parent.prototype;


var i;

for( i in parent.prototype ) {
child.prototype[i] = parent.prototype[i];
}


child.prototype.constructor = child;
child.parent = parent;

}

它有效,但我不明白“child.prototype.constructor = child”部分。没有它,该功能仍然有效。

这条线的目的是什么?

最佳答案

没有。你是在哪里找到那个东西的。它混合了两种方法:

经典原型(prototype)继承

function inherit(child, parent) {
var f = function() {}
f.prototype = parent.prototype;

child.prototype = new f();
child.prototype.constructor = child;
}

此函数创建一个新对象,该对象直接继承自 parent 函数的原型(prototype)对象。它是 Object.create() 的旧式同义词.这样,原型(prototype)链就建立起来了——child 的所有实例也都继承自 parent.prototype。因为生成了一个新对象来覆盖 child.prototype"constrcutor" property needs to be updated .

混合继承

这个函数只是遍历父对象的原型(prototype)对象的所有属性,并将它们复制到子对象的原型(prototype)对象中。这正是常见的辅助函数 extend 所做的。它没有重置子函数的“原型(prototype)”属性,但也没有建立继承链。

function extend(child, parent) {
for (var i in parent.prototype ) {
child.prototype[i] = parent.prototype[i];
}
}

你是对的,行

child.prototype.constructor = child;

在这里毫无用处 - “constructor”属性不可枚举,不会受到 extend 的影响。

此外,您的函数将子函数对象的“父”属性设置为父函数,这不是必需的:

child.parent = parent;

关于javascript - 为什么我需要为扩展函数设置构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183271/

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