建構函式和繼承方法

2022-09-08 01:27:11 字數 2129 閱讀 3544

建構函式

類的宣告

1.function宣告

function animal(name)

2.class宣告

class animal

}

類的例項化

通過 new 操作符例項化

let animal = new animal('pig')

類的繼承

//

借助建構函式實現繼承

function

parent1 ()

function

child1 ()

//不足 ,不能完全繼承parent1原型上的屬性和方法

// 例如 定義 parent1.prototype.pname = 'pname' child1就無法繼承

//

借助原型鏈實現繼承

function

parent2 () ;

function

child2()

child2.prototype = new

parent2();

//不足, 如果在建構函式中存在乙個物件,那麼修改乙個例項會影響另乙個例項的物件引數,

//因為 s1.__proto__ === s2.__proto__ 公用乙個原型物件,裡面的arr又是引用型別的值

s1 = new

child2();

s2 = new

child2();

s1.arr.push(4)

console.log(s1.arr,s2.arr)

//(4) [1, 2, 3, 4] (4) [1, 2, 3, 4]

//

組合方式1

function

parent31()

function

child31 ()

child31.prototype = new parent31(); //

獲取原型上的屬性和方法

var s3 = new

child31();

var s4 = new

child31();

s3.arr.push(4)

console.log(s3.arr,s4.arr)

//[1,2,3,4] [1,2,3]

//組合優化2,減少parent31建構函式執行次數

function

parent33()

function

child33 ()

var test= new

child33();

child33.prototype = parent33.prototype; //

獲取原型上的屬性和方法

//因為以上兩種繼承方式的 prototype 是乙個導致 他們的constructor是一樣的

console.log(test instanceof child33, test instanceof parent33) //

true true

//組合優化3

function

parent5()

function

child5 ()

var test2= new

child5();

child5.prototype = object.create(parent5.prototype);

child5.prototype.constructor = child5

方法建立乙個新物件,使用現有的物件來提供新建立的物件的__proto__

獲取原型上的屬性和方法 ,更改constructor

console.log(test2 instanceof child5, test2 instanceof parent5) //

true false

//

es6 class 繼承方式 extends

class a

say()

}// 使用 extends b繼承a的,例項後有instanceof問題

class b extends a

}

建構函式和繼承

建構函式和繼承 左直拳有同事用到了泛型,卻編譯通不過 public class class1 public class class2 class1 以為是泛型的原因。問到我,我也是支支吾吾,閃爍其詞,一會兒說繼承的基類不用再寫泛型變數,一會兒又說可能是建構函式用了泛型。試了一下,才知道根本不關泛型的...

建構函式和繼承

建構函式和繼承 左直拳有同事用到了泛型,卻編譯通不過 public class class1 public class class2 class1 以為是泛型的原因。問到我,我也是支支吾吾,閃爍其詞,一會兒說繼承的基類不用再寫泛型變數,一會兒又說可能是建構函式用了泛型。試了一下,才知道根本不關泛型的...

C 繼承建構函式和委派建構函式

如果我們在構造b的時候想要擁有a這樣的構造方法的話,就必須乙個乙個的透傳各個介面,那麼這是很麻煩的derived int va base va derived char c base c 改寫成這樣 使用繼承建構函式 using base1 base1 而且,更神奇的是,c 11標準繼承建構函式被設...