Javascript继承与简洁的原型(prototype)赋值语法

标签 javascript oop inheritance

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

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

我使用这种技术是因为我认为标准语法过于冗长和稀疏:

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

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

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

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

最佳答案

Is merging the two prototypes the solution?

是的。

How?

只需编写一个循环来运行对象文字并将每个属性合并到原型(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继承与简洁的原型(prototype)赋值语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230696/

相关文章:

java - 在 Java 或其他 OO/非函数式语言中表示复杂真值表的最佳方式是什么?

尽管设置了私有(private)属性,但 Typescript getter 返回 undefined

javascript - 如何在 Leaflet 中显示超出特定缩放级别的标签?

java - finish() 如何在 OnClick 事件中工作?

c++ - 如果我是唯一一个直接访问对象的人,为什么我应该将属性设为私有(private)?

javascript - 从子对象修改原型(prototype)上的字段

php - 抽象父级使用子级别名

javascript - 已证明大规模可靠的所见即所得编辑器有哪些?

javascript - 添加和调整文本和符号

javascript - 分配给变量的基本 node.js 回调