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

全國(guó)咨詢/投訴熱線:400-618-4000

js繼承方式及其優(yōu)缺點(diǎn)是什么?

更新時(shí)間:2023年06月20日11時(shí)43分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

  在JavaScript中,有多種方式可以實(shí)現(xiàn)繼承。下面是一些常見的繼承方式以及它們的優(yōu)缺點(diǎn):

  1.原型鏈繼承

  原型鏈繼承通過將一個(gè)對(duì)象的實(shí)例作為另一個(gè)對(duì)象的原型來實(shí)現(xiàn)繼承。這種方式使用prototype屬性來建立對(duì)象之間的連接。

  優(yōu)點(diǎn):

  ·簡(jiǎn)單易懂,容易實(shí)現(xiàn)。

  ·可以繼承父對(duì)象的屬性和方法。

  缺點(diǎn):

  ·所有實(shí)例共享父對(duì)象的屬性,一個(gè)實(shí)例的修改會(huì)影響到其他實(shí)例。

  ·無法向父對(duì)象傳遞參數(shù)。

  ·無法訪問父對(duì)象的非原型屬性。

function Parent() {
  this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
};

function Child() {
  this.name = 'Child';
}

Child.prototype = new Parent();

var child = new Child();
child.sayHello();  // 輸出:Hello, Child

  2.構(gòu)造函數(shù)繼承

  構(gòu)造函數(shù)繼承通過在子類構(gòu)造函數(shù)內(nèi)部調(diào)用父類構(gòu)造函數(shù)來實(shí)現(xiàn)繼承。這種方式使用 call 或 apply 方法將父類的屬性和方法應(yīng)用于子類。

  優(yōu)點(diǎn):

  ·可以在子類構(gòu)造函數(shù)中傳遞參數(shù)給父類構(gòu)造函數(shù)。

  ·每個(gè)實(shí)例都有自己的屬性副本。

  缺點(diǎn):

  ·無法繼承父類原型上的方法,每個(gè)實(shí)例都會(huì)創(chuàng)建一個(gè)副本。

  ·無法實(shí)現(xiàn)父類原型鏈上的方法復(fù)用。

function Parent(name) {
  this.name = name || 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
};

function Child(name) {
  Parent.call(this, name || 'Child');
}

var child = new Child();
child.sayHello();  // 拋出錯(cuò)誤:child.sayHello is not a function

  3.組合繼承

  組合繼承結(jié)合了原型鏈繼承和構(gòu)造函數(shù)繼承的優(yōu)點(diǎn),通過在子類構(gòu)造函數(shù)中調(diào)用父類構(gòu)造函數(shù),并將父類的原型賦值給子類的原型來實(shí)現(xiàn)繼承。

  優(yōu)點(diǎn):

  ·實(shí)例既可以訪問父類構(gòu)造函數(shù)的屬性,也可以訪問父類原型上的方法。

  ·每個(gè)實(shí)例都有自己的屬性副本,且可以共享父類原型上的方法。

  缺點(diǎn):

  ·調(diào)用了兩次父類構(gòu)造函數(shù),造成了不必要的性能消耗。

function Parent(name) {
  this.name = name || 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello, ' + this.name);
};

function Child(name) {
  Parent.call(this, name || 'Child');
}

Child.prototype = new Parent();

var child = new Child();
child.sayHello();  // 輸出:Hello, Child

   4.原型式繼承


       原型式繼承通過創(chuàng)建一個(gè)臨時(shí)的構(gòu)造函數(shù),將傳入的對(duì)象作為該構(gòu)造函數(shù)的原型,并返回該構(gòu)造函數(shù)的實(shí)例來實(shí)現(xiàn)繼承。

  優(yōu)點(diǎn):

  ·簡(jiǎn)單易懂,適用于簡(jiǎn)單的對(duì)象繼承。

  缺點(diǎn):

  ·所有實(shí)例共享父對(duì)象的屬性,一個(gè)實(shí)例的修改會(huì)影響到其他實(shí)例。

  ·無法向父對(duì)象傳遞參數(shù)。

  ·無法訪問父對(duì)象的非原型屬性。

function createObject(obj) {
  function F() {}
  F.prototype = obj;
  return new F();
}

var parent = {
  name: 'Parent',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};

var child = createObject(parent);
child.name = 'Child';
child.sayHello();  // 輸出:Hello, Child

  以上是一些常見的JavaScript繼承方式及其優(yōu)缺點(diǎn)。選擇適合自己需求的繼承方式很重要,可以根據(jù)具體情況選擇合適的方式實(shí)現(xiàn)繼承。

0 分享到:
和我們?cè)诰€交談!