js原型繼承-筆記
阿新 • • 發佈:2021-07-11
原型物件的繼承
js中物件間存在原型鏈的關係,所以就有對應存在的原型繼承的方法,這裡記錄一下其中一種。
call函式的使用
function People(name, age) {
this.name = name;
this.age = age;
this.energy = 100;
}
function Teacher(name, age, subject) {
People.call(this, name, age);
this.subject = subject;
}
call函式呼叫People的屬性,相當於搬入了this所在的名稱空間中,等同於
function Teacher(name, age, subject) { this.name = name; this.age = age; this.energy = 100; this.subject = subject; }
因此,父對像中的不用傳入引數的屬性就不需要在call中寫入
建立一個父子關係?
由上述程式碼產生的Teacher只是繼承了People的屬性,而在原型鏈中並沒有與之對應的關係,所以接下來就需要解決這個問題
Teacher.prototype = Object.create(People.prototype);
使用Object.create方法,我們為Teacher建立了與People相一致的原型,在console中輸入Teacher.prototype
進行檢驗,發現Teacher的建立器也邊為People,再對此進行修正
Object.defineProperty(Teacher.prototype, 'constructor', { value: Teacher, enumerable: false, // so that it does not appear in 'for in' loop writable: true });
再次進行檢驗,就ok了