首页 > 解决方案 > 以与类扩展相同的方式使用构造函数?

问题描述

为了便于理解原型,我一直在使用类。从逻辑上讲,扩展一个类可以让您从该基类继承。我将如何使用函数构造函数执行以下代码?:

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;
   }

但是然后我将如何拥有一个继承这些的运动员构造函数,就像我可以通过扩展一个类一样?

标签: javascript

解决方案


有了这个类,Athlete 的原型链是:

instance <- Athlete.prototype <- Person.prototype

对于Functions,实例的内部原型是.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());


推荐阅读