2016-04-25 52 views
-1

我有一個類,我使用它的方法作爲事件監聽器,所以我不在方法中使用thisthatJavaScript繼承和單詞「this」和「that」

這是基類:

function Modal(){ 
    var that = this; 
    this.opened = false; 
    this.open = function(){ 
     that.opened = true; 
     var id = this.id; 
     // more code 
    }; 
    this.close = function() { 
     if (that.opened) // do something; 
    }; 
} 

這是繼承的類:

function ModalBook(){ 
    var that = this; 
    this.open = function(){ 
     that.opened = true; 
     var id = this.id; 
     // more code 
    }; 
} 
ModalBook.prototype = new Modal(); 

var modalBook = new ModalBook(); 

現在的模式打開時的modal.opened值爲true,但在關閉時該值爲false 。

論的this.close線調試,我看到thatModal一個實例,modalBookModalBook一個實例。

所以我的問題是:如何在modalBook這兩種方法中保留this的值?

+0

您可以爲此創建一個小提琴嗎? –

回答

2

發生了什麼事情是ModalBook.prototype=new Modal()ModalBook是'inheriting'Modal。變量屬於其範圍內的每個構造函數,並且屬性被覆蓋。所以:

  • thatModal將在Modal
  • that留在本地將ModalBookModalBook
  • 的instante但是,這會存在被ModalBook.open()(你overwritting另一個)的唯一方法open()其中thatModalBook的一個實例,而其他that不在該範圍內。

我認爲你有一個設計問題。也許使用that的名稱不同的屬性。

1

問題

ModalBook.prototype = new Modal();意味着所有新ModalBook分之一,單一的,新的模態對象,這個模型對象處於關閉方法的that

此對象是不是爲每個新的ModalBook重新創建。這是原型繼承。


修復

如果你這樣做是正確,沒有必要捕捉this

傳統上,這是一種更好的編碼方式。

var Modal = function(){ return this; }; 
Modal.prototype = { 
    opened : false, 
    open : function(){ 
     this.opened = true; 
     var id = this.id; 
     // more code 
    }, 
    close : function() { 
     if (this.opened) // do something; 
    }, 
}; 

// Old IE may not have Object.assign or Object.create. shims available. 
var ModalBook = function(){ Modal.call(this); return this; }; 
ModalBook.prototype = Object.assign(Object.create(Modal.prototype), { 
    open : function(){ 
     this.opened = true; 
     var id = this.id; 
     console.log('open2'); 
    } 
}); 

var modalBook = new ModalBook(); 

沒有構造

或者,如果你不喜歡使用構造都和我一樣。

/* In ES6. Runs on Chrome, Firefox, Edge, Safari. Use Babel to run on IE. */ 

const Modal = { 
    opened: false, 
    create () { return Object.create(Modal).initialise(); }, 
    initialise() { return this; }, 
    open  () { /* ... */ }, 
    close  () { /* ... */ }, 
}; 

const ModalBook = { 
    __proto__ : Modal, 
    create () { return Object.create(ModalBook).initialise(); }, 
    open  () { /* ... */ }, 
}; 

var modalBook = ModalBook();