轉載請註明出處
在JavaScript
中,對象的繼承大體分爲5種。分別是:javascript
經典繼承適用於對象和對象之間的繼承
下面是詳細介紹:html
先定義兩個構造函數Animal和Catjava
function Animal(){ this.species = "動物"; } function Cat(name,color){ this.name = name; this.color = color; }
上面定義了兩個函數,一個是Cat,一個是Animal,怎麼樣才能是Cat繼承Animal。app
使用call或apply方法,將父對象的構造函數綁定在子對象上。函數
function Cat(name,color){ Animal.apply(this, arguments); this.name = name; this.color = color; } var cat1 = new Cat("大毛","黃色"); alert(cat1.species); // 動物
直接使用prototype屬性,把Cat.prototype的原型設置爲Animal實例或者Animal.prototype測試
// 指向Animal實例 Object.setPrototypeOf(Cat.prototype, new Animal()) /* * 上一行也能夠這麼寫 * Cat.prototype.__proto__ = new Animal(); */ var cat1 = new Cat("大毛","黃色"); alert(cat1.species); // 動物 // 指向Animal.prototype // 這裏要對Animal作一個改進,把不變的屬性放到prototype中去 function Animal(){ } Animal.prototype.species = "動物"; Object.setPrototypeOf(Cat.prototype, Animal.prototype) /* * 上一行也能夠這麼寫 * Cat.prototype.__proto__ = Animal.prototype */ var cat1 = new Cat("大毛","黃色"); alert(cat1.species); // 動物
把父對象的全部屬性和方法,拷貝進子對象。網站
var p = Parent.prototype; var c = Child.prototype; for (var i in p) { c[i] = p[i]; }
Class 能夠經過extends
關鍵字實現繼承,這比 ES5 的經過修改原型鏈實現繼承,要清晰和方便不少。this
// 在constructor中調用super() class Parent { constructor (x, y) { this.x = x this.y = y } test = '測試' } class Child extends Parent { constructor (x, y, z) { super(x,y) this.z = z } } let child = new Child(1, 2, 3) child.test // 測試
適用於對象和對象之間的繼承prototype
let a = { test: 'name' } // 經過對象字面量建立的對象沒有原型 // a.prototype === undefined // a let b = { name: 'test' } function C() {} C.prototype = a b = new C() b.test // name
對象的繼承除了上面常見的5種方式外,你也能夠把他們組合來實現繼承。code
歡迎瀏覽個人 我的網站