【发布时间】:2017-09-02 11:35:48
【问题描述】:
我有 2 个基类,比如 ParentClass1 和 ParentClass2。现在我想对ChildClass做多重原型继承。
使用单父类,我的代码如下。
var ParentClass = function() {
};
ParentClass.prototype.greetUser = function(name) {
console.log('Hi. Hello,', name);
};
var ChildClass = function(name) {
this.greetUser(name);
};
ChildClass.prototype = Object.create(ParentClass.prototype);
var obj = new ChildClass('John');
// Hi. Hello, John
现在,当我必须从 2 个父类 继承时,我尝试了以下代码。
var ParentClass1 = function() {
};
ParentClass1.prototype.greetUser = function(name) {
console.log('Hi. Hello,', name);
};
var ParentClass2 = function() {
};
ParentClass2.prototype.askUser = function(name) {
console.log('Hey, how are you,', name);
};
var ChildClass = function(name) {
this.askUser(name);
this.greetUser(name);
};
ChildClass.prototype = Object.create(ParentClass1.prototype);
ChildClass.prototype = Object.create(ParentClass2.prototype);
var obj = new ChildClass('John');
// Error.
但这似乎只接受最后提到的 Object.create() 。
所以后来,它尝试将第二个Object.create() 切换到Object.assign(),然后它工作正常。
ChildClass.prototype = Object.create(ParentClass1.prototype);
ChildClass.prototype = Object.assign(ChildClass.prototype, ParentClass2.prototype);
但我担心Object.assign() 正在做克隆。那么这是正确的方法吗?或者有没有更好的选择?
很抱歉提出这个问题,冗长。提前致谢。
【问题讨论】:
-
Object.assign不进行深度克隆。它很浅。
标签: javascript inheritance prototypal-inheritance