轉載請註明出處javascript
在JavaScript
中,對象的繼承大體分爲5種。分別是:html
經典繼承適用於對象和對象之間的繼承java
下面是詳細介紹:app
先定義兩個構造函數Animal和Cat函數
function Animal(){
this.species = "動物";
}
function Cat(name,color){
this.name = name;
this.color = color;
}
複製代碼
上面定義了兩個函數,一個是Cat,一個是Animal,怎麼樣才能是Cat繼承Animal。測試
使用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.prototypeui
// 指向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); // 動物
複製代碼
把父對象的全部屬性和方法,拷貝進子對象。this
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
複製代碼
Class 能夠經過extends
關鍵字實現繼承,這比 ES5 的經過修改原型鏈實現繼承,要清晰和方便不少。spa
// 在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 // 測試
複製代碼
適用於對象和對象之間的繼承
let a = {
test: 'name'
}
// 經過對象字面量建立的對象沒有原型
// a.prototype === undefined
// a
let b = {
name: 'test'
}
function C() {}
C.prototype = a
b = new C()
b.test // name
複製代碼
對象的繼承除了上面常見的5種方式外,你也能夠把他們組合來實現繼承。
歡迎瀏覽個人我的網站