標籤:
首先都知道js類是通過原型和構造器實現的,js中將類的方法放在function的prototype裡面了,它的每一個執行個體對象都可以獲得該類的方法,因此實現了繼承
1 function Person(name,sex){ 2 this.name = name; 3 this.sex = sex; 4 } 5 Person.propotype.sayHello = function(){ 6 console.log(this.name + "say hello"); 7 } 8 function Female(age){ 9 this.age = age;10 };11 //Female也是Person,那麼Female怎麼去實現繼承呢?
實現繼承:
Female.prototype == Person.prototype //錯誤的實現
這種方式只是簡單的將Femal的原型指向了Person的原型,即Female和Person指向同一個原型,當子類Female增刪改原型方法時,父類Person的原型也會被改變,所以該方法是不可取的。那麼應該怎麼做呢?
就是讓Female的__proto__屬性指向Person的prototype對象,而不是直接把prototype指向Person的prototype。
但是Femal.prototyoe.__proto__ = Person.prototype; //也是不正確的
因為__proto__不是一個標準的文法,在有些瀏覽器是擷取不到這個屬性的。
那麼合理的做法應該是:讓Female的prototype指向一個obejct,這個object的__proto__指向Person的prototype
大概實現如:
那麼具體實現是:通過Object.create()複製一個新的prototype(該方法是在ES5中出現的,之前版本可以通過屬性遍曆實現淺拷貝)
Female.prototype = Object.create(Person.prototype);
console.log(girl instanceof Female); //false 這裡又為什麼是false?
這裡就還包含了一個問題,就是constructor的指向不對,因為是clone過來的prototype,那麼prototype中的constructor還是指向Person(),那麼需要把
Femal.construtor = Femal; 這樣就徹底實現了繼承
一般可以將該實現封裝成一個方法
1 function inherit(superType,subType){2 var _propotype = Object.create(superType.propotype);3 _propotype.construcotr = subType;4 _propotype.propotype = _propotype;5 }
那麼完整代碼:
1 function Person(name,sex){ 2 this.name = name; 3 this.sex = sex; 4 } 5 Person.propotype.sayHello = function(){ 6 console.log(this.name + "say hello"); 7 } 8 function Female(name,sex,age){ 9 Person.call(this, name, sex);10 this.age = age;11 };12 //Female也是Person,那麼Female怎麼去實現繼承呢?13 // 在繼承函數之後寫自己的方法,否則會被覆蓋14 Female.prototype.printAge = function(){15 console.log(this.age);16 };17 var fm = new Female(‘Byron‘, ‘m‘, 26);18 fm.sayHello();
js繼承實現