js原型繼承--使用構造函數和空函數修復原型鏈解決的問題
//父類構造函數
function People(props){
this.name = props.name;
this.speak = function (){
alert(this.name + ' is speaking');
}
}
//子類構造函數
function Teacher(props){
People.call(this,props);
this.teach = function(){
alert(this.name+' is teaching');
}
this.speak = function (){
alert('when '+this.name+'is speaking, he is teaching')
}
}
//空函數用來修復原型鏈
function Adapter(){}
Adapter.prototype = People.prototype;
Teacher.prototype = new Adapter();
//修復constructor
Teacher.prototype.constructor = Teacher;
People.prototype.gender = 'male';
//Teacher.prototype.gender = 'female';
var teacher = new Teacher({name:'jack'});
var people = new People({name:'jim'});
teacher.speak();
teacher.teach();
alert(people.gender);
alert(teacher.gender);//如果不修復原型鏈則teacher的原型鏈關系:__proto__-->Teacher.prototype-->Object.prototype-->null
//則People.prototype擴展屬性的時候無法繼承到
//如果直接Teacher.prototype=People.prototype, 則會引用同一個prototype, 給Teacher.prototype擴展屬性的時候會影響到People的實例對象
總結就是:
- 每個對象都有一個proto屬性
- 每個函數都有一個prototype屬性
- 定義一個函數隱含的有
- js訪問一個對象的屬性或方法的時候會首先在這個對象里面尋找,如果找不到則去原型鏈指針prototype指向的對象去找,如果找不到會一直沿著prototype找下去
- 一個對象的prototype正常應該指向繼承對象
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。