gpt4 book ai didi

javascript - 斯托扬·斯特凡诺夫 : JavaScript Patterns - "The Default Pattern"

转载 作者:行者123 更新时间:2023-11-28 15:47:57 25 4
gpt4 key购买 nike

第 6 章(代码重用模式)中有以下示例:

// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}

// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};

// empty child constructor
function Child(name) {}

// inheritance magic happens here
inherit(Child, Parent);

在“经典模式 #1 — 默认模式”部分中,inherit() 函数的实现是:

function inherit(C, P) {
C.prototype = new P();
}

在“使用模式 #1 时的缺点”部分中,有以下示例:

var s = new Child('Seth');
s.say(); // "Adam"

我不明白以下作者的解释:

This is not what you’d expect. It’s possible for the child to pass parameters to the parent’s constructor, but then you have to do the inheritance every time you need a new child, which is inefficient, because you end up re-creating parent objects over and over.

子级如何将参数传递给父级的构造函数?如果不通过隐藏的原型(prototype)属性,如何在构造后更改子对象的原型(prototype)?谁能给我举个例子,作者的意思是什么?

最佳答案

you have to do the inheritance every time you need a new child, which is inefficient, because you end up re-creating parent objects over and over.

这并不是低效,如果 done properly 则不会创建更多对象。事实上,每次传递参数和调用父构造函数时,您都必须进行显式继承。

function Child(name) {
Parent.call(this, name); // apply the parent constructor on new instance
// to set up instance variables like `name`
}

// inheritance stuff happens here
Child.prototype = Object.create(Parent.prototype);

...当您了解原型(prototype)链如何工作以及什么时,这并不神奇 Object.create确实如此。

关于javascript - 斯托扬·斯特凡诺夫 : JavaScript Patterns - "The Default Pattern",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609821/

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