Stoyan Stefanov:JavaScript模式-“默认模式” [英] Stoyan Stefanov: JavaScript Patterns - "The Default Pattern"

查看:58
本文介绍了Stoyan Stefanov:JavaScript模式-“默认模式”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In chapter 6 (Code Reuse Patterns) there is following example:

// 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()函数的实现为:

In section "Classical Pattern #1 — The Default Pattern" the implementation of the inherit() function is:

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

在使用模式1时的缺点部分中的示例如下:

In the section "Drawbacks When Using Pattern #1" is the following example:

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

我不理解以下作者的解释:

I don't understand the following author's explanation:


这不是您期望的。孩子有可能将
参数传递给父级的构造函数,但是每当您需要一个新的孩子时,您都必须进行
继承,这是效率低下的
,因为您最终会-一遍又一遍地创建父对象。

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属性,如何在构造后更改子对象的原型?谁能给我一个例子,作者是什么意思?

How is it possible for the child to pass a parameter to the parent's constructor? And how is it possible to change the prototype of an child object after construction if not through the hidden prototype property? Could anyone please give me an example for that, what the author means?

推荐答案


每当您需要一个新的子代时都要进行继承,这效率很低,因为您最终要一遍又一遍地重新创建父对象。

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.

这不是低效率的,如果正确完成,则不会创建其他对象。确实,每次传递参数和调用父构造函数时,您都必须进行显式继承。

It's not inefficient, not further objects are created if done properly. Indeed, you will have to do explicit inheritance every time for passing parameters and invoking parent constructors.

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);

...当您了解原型链的工作原理以及 Object.create

… which is no magic when you understand how the prototype chain works and what Object.create does.

这篇关于Stoyan Stefanov:JavaScript模式-“默认模式”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆