JS 繼承
阿新 • • 發佈:2022-02-23
1 原型鏈繼承
//父類 function Person(name,age){ this.name = name || 'unknow' this.age = age || 0 } //子類 function Student(name){ this.name = name this.score = 80 } //繼承 Student.prototype = new Person(); Student.prototype.constructor = Student; var stu = new Student('lucy'); console.log(stu.name); //lucy --子類覆蓋父類的屬性 console.log(stu.age); // 0 --父類的屬性 console.log(stu.score); // 80 --子類自己的屬性 *原型繼承共享引用型別(方法)* 共享方法可以,因為方法本身程式碼不變,就是被共享的. 但有些引用型別自身變化,如下 //父類 function Person(){ this.hobbies = ['music','reading'] } //子類 function Student(){ } //繼承 Student.prototype = new Person(); Student.prototype.constructor = Student; var stu1 = new Student(); var stu2 = new Student(); stu1.hobbies.push('basketball'); console.log(stu1.hobbies); // ["music", "reading", "basketball"] console.log(stu2.hobbies); // ["music", "reading", "basketball"]
2 建構函式繼承
*建構函式不共享引用型別和方法* //父類 function Person(){ this.hobbies = ['music','reading'] } //子類 function Student(){ Person.call(this); } var stu1 = new Student(); var stu2 = new Student(); stu1.hobbies.push('basketball'); console.log(stu1.hobbies); // ["music", "reading", "basketball"] console.log(stu2.hobbies); // ["music", "reading"] *建構函式可以給父類傳參* //父類 function Person(name){ this.name = name; } //子類 function Student(name){ Person.call(this,name); //傳參Person(name) } var stu1 = new Student('lucy'); var stu2 = new Student('lili'); console.log(stu1.name); // lucy console.log(stu2.name); // lili
3 組合繼承
某些引用型別屬性使用建構函式繼承不共享,方法使用原型鏈繼承共享。
不論是建構函式還是原型鏈, 基本型別都是不共享的(基本型別與引用型別賦值的區別)
//父類 function Person(name){ this.hobbies = ['music','reading']; } Person.prototype.say = function(){ console.log('i am a person'); } //子類 function Student(name){ Person.call(this); //建構函式繼承(繼承屬性)本地hobbies } Student.prototype = new Person(); //原型繼承(繼承方法) 原型鏈hobbies和say Student.prototype.constructor = Student; //其實是本地hobbies比原型鏈的hobbies優先,實現組合繼承 var stu1 = new Student('lucy'); var stu2 = new Student('lili'); stu1.hobbies.push('basketball'); console.log(stu1.hobbies); // ["music", "reading", "basketball"] console.log(stu2.hobbies); // ["music", "reading"] console.log(stu1.say === stu2.say); // true