日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

JS 怎样模拟类的特性

發布時間:2025/3/21 63 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JS 怎样模拟类的特性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

function Animal(){}

function Dog(){}

1.實現 Dog 繼承 Animal

Dog.prototype = Object.create(Animal.prototype)

背景知識:要實現 Dog 繼承 Animal, 就是要實現 new Dog() instanceof Animal 為真就是要實現 new Dog().__proto__.__proto__ === Animal.prototype即實現 Animal.prototype 在 new Dog() 的原型鏈上 實現過程:根據js原型鏈的相關知識, 有 new Dog().__proto__ === Dog.prototype要實現繼承, 就可以令 Dog.prototype.__proto__ === Animal.prototype也就是 Dog.prototype = Object.create(Animal.prototype) 復制代碼// 測試代碼(直接在瀏覽器控制臺中運行):function Animal(){}function Dog(){}Dog.prototype = Object.create(Animal.prototype);console.log(new Dog() instanceof Animal);//結果為 true 復制代碼

2.實現 Dog 與 Animal 類之間的多態,方法重寫等

// 測試代碼(直接在瀏覽器控制臺中運行):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());//結果為 I’m Animal//子類Dog重寫父類Animal的name方法Dog.prototype = Object.create(Animal.prototype,{name:{value(){return 'Dog';}}});console.log(new Dog().say());//結果為 I’m Dog 復制代碼

3.完善類的模擬

// 測試代碼(直接在瀏覽器控制臺中運行):function Animal(){}function Dog(){}Dog.prototype = Object.create(Animal.prototype);console.log(Dog.prototype.constructor);//結果為 ? Animal(){}//上面的這個輸出是不對的, 結果應該是 ? Dog(){}, 解決方法Dog.prototype = Object.create(Animal.prototype,{constructor:{value:Dog,enumerable:false} });console.log(Dog.prototype.constructor);// 結果為 ? Dog(){} 復制代碼

轉載于:https://juejin.im/post/5ca20f32f265da308a2897f3

總結

以上是生活随笔為你收集整理的JS 怎样模拟类的特性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。