我有这段代码。
Animal = function(age)
{
Animal.prototype.age = age;
};
Animal.prototype.constructor = Animal;
Animal.prototype.Walk = function()
{
console.log("Animal Walking");
};
Pet = function(age, name)
{
Pet.prototype.name = name;
};
Pet.prototype.constructor = Pet;
Pet.prototype = Object.create(new Animal());
Pet.prototype.DoTricks = function()
{
console.log(this.name + " is doing tricks!");
};
var pet = new Pet(5, "Barney");
console.log(pet);
所有动物都有年龄,可以走路。 Pet通过其原型继承Animal。 宠物有名字,可以做伎俩,也有年龄,可以走路。
如何组织我的代码来实现此行为?目前我可以做到这样,宠物可以走路,但他们的年龄是不确定的,因为我无法通过构造函数传递它的年龄。
非常感谢!
答案 0 :(得分:1)
要将构造函数中的参数传递给 base ,您可以使用.call()
或.apply()
执行基础构造函数:
var Pet = function (age, name) {
Animal.call(this, age);
// ...
};
两者都允许使用相同的上下文(this
)值调用基础构造函数。
您还只想修改任何构造函数之外的prototype
,因为它的属性及其值将在所有实例之间共享。
var a = new Animal(10);
var b = new Animal(15);
console.log(a.age); // 15 rather than its own 10
要为每个实例设置其他属性,您需要修改上下文this
:
var Animal = function (age) {
this.age = age;
};
var Pet = function (age, name) {
Animal.call(this, age);
this.name = name;
};
关于constructor
属性:
初始prototype
对象已经设置了constructor
属性。所以,通常不需要自己设置它:
Animal.prototype.constructor = Animal;
除非您完全替换初始prototype
对象。对于这种情况,您需要在之后重置constructor
,或者将其设置为要替换的初始对象。
Pet.prototype = Object.create(Animal.prototype);
Pet.prototype.constructor = Pet;