[js] js怎样避免原型链上的对象共享?
生活随笔
收集整理的這篇文章主要介紹了
[js] js怎样避免原型链上的对象共享?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
[js] js怎樣避免原型鏈上的對象共享?
組合繼承
優勢
劣勢
需要手動綁定constructor 封裝性一般 重復調用父類性能損耗🌰
function Parent (name, friends) {// 私有的部分this.name = name;this.friends = friends; } Parent.prototype = {// 公有的寫這里constructor: Parent,// 需要手動綁定share: [1, 2, 3],log: function () {return this.name;} }// 封裝性一般 function Child (name, friends, gender) {Parent.call(this, name, friends); // 這里調用了一次Parentthis.gender = gender; } Child.prototype = new Parent(); // 這里又調用了一次Parent Child.prototype.constructor = Child;//需要手動修改constructor寄生組合繼承
寄生組合式繼承
雜糅了原型鏈式、構造函數式、組合式、原型式、寄生式而形成的一種方式:
主要是解決了組合繼承的唯一缺點:多次調用Parent
優點:
缺點
需要手動綁定constructor 需要調用額外的方法 封裝性一般🌰
function Parent (name, friends) {this.name = name;this.friends = friends; } Parent.prototype = {constructor: Parent,//需要手動綁定constructorshare: [1, 2, 3],log: function () {return this.name} } function Child (name, friends, gender) {Parent.call(this, name, friends);this.gender = gender; } function proto(child, parent) {let clonePrototype = Object.create(parent.prototype)child.prototype = clonePrototypechild.prototype.constructor = child } proto(Child,Parent);ES6 class
🌰
class Parent {constructor(name, friends) { // 該屬性在構造函數上,不共享this.name = namethis.friends = friends}log() { // 該方法在原型上,共享return this} } Parent.prototype.share = [1, 2, 3] // 原型上的屬性,共享class Child extends Parent {constructor(name, friends, gender) {super(name, friends)this.gender = gender} }個人簡介
我是歌謠,歡迎和大家一起交流前后端知識。放棄很容易,
但堅持一定很酷。歡迎大家一起討論
主目錄
與歌謠一起通關前端面試題
總結
以上是生活随笔為你收集整理的[js] js怎样避免原型链上的对象共享?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android preference-h
- 下一篇: android textwatcher