【发布时间】:2016-02-15 01:04:19
【问题描述】:
我通常按照以下方式实现继承。
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();
我已经阅读了this post by 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); 有关
【问题讨论】:
-
如果你使用的是 ES2015,你应该使用
class&extend -
@Amit 这显然不是他问的问题。使用
class和extend是否是一个好主意是另一个讨论的一部分。 -
@Amit - 为什么我应该使用
class和extend?如果我这样做,我最终不得不使用new,不是吗?使用class和extend比Object.assign(Object.create(...有什么优势? -
我在其中添加了 ES6 标签,因为主要问题是我可以使用 Object.create 和 Object.assign。
-
按照这种模式,您宁愿拥有
var duck = Object.assign(Object.create和var daffy = Object.create(duck)。