使用`Object.create‘进行继承的好处我一直想把我的头转到新的Object.create方法是在ECMAScript 5中介绍的。通常,当我想使用继承时,我会这样做:var Animal = function(name) { this.name = name; }Animal.prototype.print = function() { console.log(this.name); }var Dog = function() {
return Animal.call(this, 'Dog'); }Dog.prototype = new Animal();Dog.prototype.bark = function() { console.log('bark'); }我只是给狗的原型分配了一个新创建的动物对象,所有的东西都很有魅力:var dog1 = new Dog();dog1.print(); // prints 'Dog'dog1.bark(); // prints 'bark'dog1.name; //prints 'Dog'但是人们(没有解释)说Dog.prototype = new Animal();不是继承的工作方式,我应该使用Object.create方法:Dog.prototype = Object.create(Animal.prototype);这也很管用。使用Object.create还是我遗漏了什么?更新:有人说Dog.prototype = Animal.prototype;也能起作用。所以现在我完全糊涂了
3 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
new Animal()
:
//creating a new object var res = {}; //setting the internal [[prototype]] property to the prototype of Animal if (typeof Animal.prototype === "object" && Animal.prototype !== null) { res.__proto__ = Animal.prototype; } //calling Animal with the new created object as this var ret = Animal.apply(res, arguments); //returning the result of the Animal call if it is an object if (typeof ret === "object" && ret !== null) { return ret; } //otherise return the new created object return res;
Object.create
:
//creating a new object var res = {}; //setting the internal [[prototype]] property to the prototype of Animal if (typeof Animal.prototype !== "object") { throw "...."; } res.__proto__ = Animal.prototype; //return the new created object return res;
Animal
Dog.prototype = { name: undefined, __proto__: Animal.prototype};
Dog.prototype = { __proto__: Animal.prototype};
name
Dog
Animal.call(this, 'Dog');
.
Dog
Animal
添加回答
举报
0/150
提交
取消