咱們先構建一個Person的構造函數函數
function Person(name) { this.name=name; } Person.prototype.sayHi=function () { console.log(this.name+",您好"); }
而後經過構建Student構造函數演示幾種繼承方式學習
1.經過原型鏈方式進行繼承this
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纔可調用成功spa
存在缺點:Person的實例化對象時name屬性固定爲「張三」,當屢次實例化Student對象時,致使繼承的name屬性一直爲「張三」;prototype
2.在構造Student函數中使用call方式進行繼承code
function Student(age,name) { this.age=age; Person.call(this,name);//經過call方式改變this指向 } Student.prototype.study=function () { console.log("學習"); }
存在缺點:此方式在Student實例化對象,能夠調用Student原有方法study,可是沒法調用Person構造函數中的方法對象
3.組合繼承blog
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);