當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS 怎样模拟类的特性
生活随笔
收集整理的這篇文章主要介紹了
JS 怎样模拟类的特性
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
function Animal(){}
function Dog(){}
1.實(shí)現(xiàn) Dog 繼承 Animal
Dog.prototype = Object.create(Animal.prototype)
背景知識:要實(shí)現(xiàn) Dog 繼承 Animal, 就是要實(shí)現(xiàn) new Dog() instanceof Animal 為真就是要實(shí)現(xiàn) new Dog().__proto__.__proto__ === Animal.prototype即實(shí)現(xiàn) Animal.prototype 在 new Dog() 的原型鏈上 實(shí)現(xiàn)過程:根據(jù)js原型鏈的相關(guān)知識, 有 new Dog().__proto__ === Dog.prototype要實(shí)現(xiàn)繼承, 就可以令 Dog.prototype.__proto__ === Animal.prototype也就是 Dog.prototype = Object.create(Animal.prototype) 復(fù)制代碼// 測試代碼(直接在瀏覽器控制臺中運(yùn)行):function Animal(){}function Dog(){}Dog.prototype = Object.create(Animal.prototype);console.log(new Dog() instanceof Animal);//結(jié)果為 true 復(fù)制代碼2.實(shí)現(xiàn) Dog 與 Animal 類之間的多態(tài),方法重寫等
// 測試代碼(直接在瀏覽器控制臺中運(yùn)行):function Animal(){}function Dog(){}Object.defineProperties(Animal.prototype,{name:{value(){return 'Animal';}},say:{value(){return 'I’m ' + this.name();}}});//子類Dog繼承父類Animal中的方法Dog.prototype = Object.create(Animal.prototype);console.log(new Dog().say());//結(jié)果為 I’m Animal//子類Dog重寫父類Animal的name方法Dog.prototype = Object.create(Animal.prototype,{name:{value(){return 'Dog';}}});console.log(new Dog().say());//結(jié)果為 I’m Dog 復(fù)制代碼3.完善類的模擬
// 測試代碼(直接在瀏覽器控制臺中運(yùn)行):function Animal(){}function Dog(){}Dog.prototype = Object.create(Animal.prototype);console.log(Dog.prototype.constructor);//結(jié)果為 ? Animal(){}//上面的這個(gè)輸出是不對的, 結(jié)果應(yīng)該是 ? Dog(){}, 解決方法Dog.prototype = Object.create(Animal.prototype,{constructor:{value:Dog,enumerable:false} });console.log(Dog.prototype.constructor);// 結(jié)果為 ? Dog(){} 復(fù)制代碼轉(zhuǎn)載于:https://juejin.im/post/5ca20f32f265da308a2897f3
總結(jié)
以上是生活随笔為你收集整理的JS 怎样模拟类的特性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你所不知道的ASP.NET Core M
- 下一篇: 刚刚,阿里发布AI谣言粉碎机,识别准确率