日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JS 怎样模拟类的特性

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

function Animal(){}

function Dog(){}

1.實現(xiàn) Dog 繼承 Animal

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

背景知識:要實現(xiàn) Dog 繼承 Animal, 就是要實現(xiàn) new Dog() instanceof Animal 為真就是要實現(xiàn) new Dog().__proto__.__proto__ === Animal.prototype即實現(xiàn) Animal.prototype 在 new Dog() 的原型鏈上 實現(xiàn)過程:根據js原型鏈的相關知識, 有 new Dog().__proto__ === Dog.prototype要實現(xiàn)繼承, 就可以令 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.實現(xiàn) Dog 與 Animal 類之間的多態(tài),方法重寫等

// 測試代碼(直接在瀏覽器控制臺中運行):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 怎样模拟类的特性的全部內容,希望文章能夠幫你解決所遇到的問題。

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