Dog.prototype.calcAge = function () { console.log(2023 - this.birthYear) }
constPet = function (firstName, birthYear, skill) { // call() 呼叫 Dog 函式 Dog.call(this, firstName, birthYear) this.skill = skill }
Pet.prototype = Object.create(Dog.prototype) Pet.prototype.constructor = Pet
Pet.prototype.introduce = function () { console.log(`My name is ${this.firstName} and I can ${this.skill}.`) }
const aben = newPet("ABen", 2021, "bark at strangers")
console.log(aben) // Pet {firstName: 'ABen', birthYear: 2021, skill: 'bark at strangers'} aben.introduce() // My name is ABen and I can bark at strangers. aben.calcAge() // 2
使用 Object.create() 將 Dog.prototype 屬性物件設為 Pet.prototype 屬性物件的原型,使 Pet 的實例 aben 可以使用 Dog 上的 calcAge() 方法,但因為 Object.create() 不會設置新物件的 constructor 屬性,所以 Pet.prototype.constructor 仍然指向 Dog ,只能以 Pet.prototype.constructor = Pet 校正。
constPetPrototype = Object.create(DogPrototype) PetPrototype.init = function (firstName, birthYear, skill) { DogPrototype.init.call(this, firstName, birthYear) this.skill = skill } PetPrototype.introduce = function () { console.log(`My name is ${this.firstName} and I can ${this.skill}.`) }
const aben = Object.create(PetPrototype) aben.init("ABen", 2021, "bark at strangers")
console.log(aben) // {firstName: 'ABen', birthYear: 2021, skill: 'bark at strangers'}
aben.calcAge() // 2
aben.introduce() // My name is ABen and I can bark at strangers.