简洁的原型分配语法实现Javascript继承 [英] Javascript inheritance with concise prototype assignment syntax

查看:31
本文介绍了简洁的原型分配语法实现Javascript继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用这种(prototype)方法定义了两个javascript类:

I've defined two javascript classes using this (prototype) approach:

function Parent () {
    this.a = 1;
}

Parent.prototype = {
    hello : function () {
        return "Hello I'm Parent!";
    },
    setA : function (a) {
        this.a = a;
    }
};

function Child () {
    this.b = 2;
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

Child.prototype = {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
};

我之所以使用这种技术,是因为我认为它的标准语法过于冗长和稀疏:

I'm using this technique because I think that the standard syntax it's too verbose and sparse:

Child.prototype.hello = function () {...};

Child.prototype.setB = function (b) {...};

这里的问题是我覆盖 Child.prototype(继承自Parent)丢失了.setA()方法(但正确地覆盖了覆盖 .hello()).

The problem here is that I'm overwriting Child.prototype (inherited from Parent) losing .setA() method (but correctly overriding .hello()).

合并两个原型是解决方案吗?怎么样?
这种方法会导致问题吗?

Is merging the two prototypes the solution? How?
Can this approach lead to problems?

推荐答案

将两个原型合并为解决方案吗?

Is merging the two prototypes the solution?

是的

如何?

只需编写一个循环遍历对象文字并将每个属性合并到原型中即可.

Simply write a loop that runs over the object literal and merges each property into the prototype.

function inherit(Child, Parent, methods) {
    var p = Child.prototype = Object.create(Parent.prototype);
    p.constructor = Child;
    for (var m in methods)
        p[m] = methods[m];
    return p;
}

function Child () {
    Parent.call(this);
    this.b = 2;
}
inherit(Child, Parent, {
    hello : function () {
        return "Hello I'm Child!";
    },
    setB : function (b) {
        this.b = b;
    }
});

这篇关于简洁的原型分配语法实现Javascript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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