为了便于理解原型,我一直在使用类。从逻辑上讲,扩展一个类可以让您从该基类继承。我将如何使用函数构造函数做下面的代码?:
class Person {
constructor(name,age,speciality="Not Specified") {
this.name = name;
this.age = age;
this.speciality = speciality;
}
sayName() {
return this.name;
}
}
class Athlete extends Person {
constructor(name, age, speciality) {
super(name,age)
this.speciality = speciality
}
getSport() {
return "I play " + this.speciality;
}
}
let john = new Person('john', 44)
let jim = new Athlete('jim', 54, 'basketball');
我知道我应该:
function Person(name,age,speciality="Not Specified") {
this.name = name;
this.age = age;
this.speciality = speciality;
}
我假设我将sayName()
作为原型,而不是Person中的属性,如:
Person.prototype.sayName = function() {
return this.name;
}
但是,我如何拥有一个继承这些的Athlete构造函数,就像我可以扩展一个类一样?
有了这个类,运动员的原型链是:
instance <- Athlete.prototype <- Person.prototype
对于Function
s,实例的内部原型是用来构造它的函数的.prototype
属性。与类一样,new Foo()
的内部原型将是Foo.prototype
。因此,要手动扩展它,您需要将.prototype
属性设置为继承自Person.prototype
的对象:
function Person(name, age, speciality = "Not Specified") {
this.name = name;
this.age = age;
this.speciality = speciality;
}
Person.prototype.sayName = function() {
return this.name;
}
function Athlete(name, age, speciality) {
Person.call(this, name, age, speciality);
this.speciality = speciality;
}
Athlete.prototype = Object.create(Person.prototype);
Athlete.prototype.getSport = function() {
return "I play " + this.speciality;
};
let jim = new Athlete('jim', 54, 'basketball');
console.log(jim.sayName());
console.log(jim.getSport());