教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

原生JS中怎么實現(xiàn)繼承關(guān)系?

更新時間:2023年12月20日10時45分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

  在原生JavaScript中實現(xiàn)繼承關(guān)系可以使用原型鏈或者ES6中的類來實現(xiàn)。下面筆者將分別展示這兩種方式。

原生JS中怎么實現(xiàn)繼承關(guān)系

  1.原型鏈繼承

  原型鏈繼承通過將一個對象的原型設(shè)置為另一個對象,從而實現(xiàn)繼承。這種方法簡單,但也存在一些潛在問題。

// 父類構(gòu)造函數(shù)
function Animal(name) {
  this.name = name;
}

// 在父類原型上添加方法
Animal.prototype.makeSound = function() {
  console.log('Some generic sound');
};

// 子類構(gòu)造函數(shù)
function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

// 將子類的原型設(shè)置為父類的一個實例
Dog.prototype = Object.create(Animal.prototype);

// 修正子類的構(gòu)造函數(shù)指向
Dog.prototype.constructor = Dog;

// 在子類原型上添加方法
Dog.prototype.bark = function() {
  console.log('Woof! Woof!');
};

// 實例化子類
const myDog = new Dog('Buddy', 'Golden Retriever');

// 測試繼承方法和屬性
myDog.makeSound(); // 輸出: Some generic sound
myDog.bark(); // 輸出: Woof! Woof!
console.log(myDog.name); // 輸出: Buddy
console.log(myDog instanceof Dog); // 輸出: true
console.log(myDog instanceof Animal); // 輸出: true

  2.ES6類繼承

  ES6引入了class關(guān)鍵字,使得面向?qū)ο缶幊谈忧逦鸵子诶斫狻?/p>

// 父類
class Animal {
  constructor(name) {
    this.name = name;
  }

  makeSound() {
    console.log('Some generic sound');
  }
}

// 子類繼承父類
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  bark() {
    console.log('Woof! Woof!');
  }
}

// 實例化子類
const myDog = new Dog('Buddy', 'Golden Retriever');

// 測試繼承方法和屬性
myDog.makeSound(); // 輸出: Some generic sound
myDog.bark(); // 輸出: Woof! Woof!
console.log(myDog.name); // 輸出: Buddy
console.log(myDog instanceof Dog); // 輸出: true
console.log(myDog instanceof Animal); // 輸出: true

  這兩種方式都可以實現(xiàn)繼承關(guān)系,ES6的類語法更加清晰易懂,并且避免了原型鏈繼承的一些問題。

0 分享到:
和我們在線交談!