我們先構建一個Person的構造函數 然後通過構建Student構造函數演示幾種繼承方式 1.通過原型鏈方式進行繼承 註意:使用此方式進行繼承,在Student構造函數中添加原型方法應註意在改變原型指向後添加方法,上述代碼中Student實例化後,Student的方式Study1調用失敗study2 ...
我們先構建一個Person的構造函數
function Person(name) { this.name=name; } Person.prototype.sayHi=function () { console.log(this.name+",您好"); }
然後通過構建Student構造函數演示幾種繼承方式
1.通過原型鏈方式進行繼承
function Student(age){ this.age=age; }
Student.prototype.study1=function () {
console.log("我熱衷於學習");
}
Student.prototype=new Person(“張三”);//改變原型指向,指向Person的實例對象的__proto__ Student.prototype.study2=function () { console.log("我熱衷於敲代碼"); }
註意:使用此方式進行繼承,在Student構造函數中添加原型方法應註意在改變原型指向後添加方法,上述代碼中Student實例化後,Student的方式Study1調用失敗study2才可調用成功
存在缺點:Person的實例化對象時name屬性固定為“張三”,當多次實例化Student對象時,導致繼承的name屬性一直為“張三”;
2.在構造Student函數中使用call方式進行繼承
function Student(age,name) { this.age=age; Person.call(this,name);//通過call方式改變this指向 } Student.prototype.study=function () { console.log("學習"); }
存在缺點:此方式在Student實例化對象,可以調用Student原有方法study,但是無法調用Person構造函數中的方法
3.組合繼承
function Student(age,name) { this.age=age; Person.call(this,name);//通過call方式改變this指向 } Student.prototype=new Person();//改變原型的指向 Student.prototype.study=function () { console.log("學習"); }
解決了上述兩種方式出現的問題
4.拷貝繼承
var obj1={ name:"張三", age:16, sayHi:function () { console.log(this.name+",您好"); } } var obj2={}; for(var key in obj1){ obj2[key]=obj1[key]; } console.dir(obj2); console.dir(obj1);