我通常按照以下方式实现继承。
function Animal () { this.x = 0; this.y = 0;}
Animal.prototype.locate = function() {
console.log(this.x, this.y);
return this;
};
Animal.prototype.move = function(x, y) {
this.x = this.x + x;
this.y = this.y + y;
return this;
}
function Duck () {
Animal.call(this);
}
Duck.prototype = new Animal();
Duck.prototype.constructor = Duck;
Duck.prototype.speak = function () {
console.log("quack");
return this;
}
var daffy = new Duck();
daffy.move(6, 7).locate().speak();
我已经阅读了Eric Elliott的这篇文章,如果我理解正确,我可以使用Object.create
和Object.assign
来替代吗? 难道真的那么简单吗?
var animal = {
x : 0,
y : 0,
locate : function () {
console.log(this.x, this.y);
return this;
},
move : function (x, y) {
this.x = this.x + x;
this.y = this.y + y;
return this;
}
}
var duck = function () {
return Object.assign(Object.create(animal), {
speak : function () {
console.log("quack");
return this;
}
});
}
var daffy = duck();
daffy.move(6, 7).locate().speak();
顺便提一下,按照惯例构造函数应该大写,那么充当构造函数的对象字面量也应该大写吗?
我意识到这里有许多关于new
与Object.create
的问题讨论,但它们通常似乎涉及 Duck.prototype = new Animal();
与 Duck.prototype = Object.create(Animal.prototype);
的区别。
class
和extend
。 - Amitclass
和extend
是一个独立的讨论话题。 - nilsclass
和extend
?如果我这样做,我不是还得使用new
吗?使用class
和extend
相比于Object.assign(Object.create(...
有什么优势呢? - user5325596var duck = Object.assign(Object.create
和var daffy = Object.create(duck)
。 - a better oliver