2016-11-28 57 views
1

我在網頁中編寫不同的事件HTML上下文的解析器。如何訪問從子類型調用的超類型的js事件對象?

的基本結構是這樣的:

註冊事件,並將其鏈接到一個分析器功能。

elem.addEventListener(
    'click', 
    (e) => { 
     let parser = new UiResultsItemInfoParser(e); 
     eventInfo = parser.evntInfo; 
     submitEvnt(eventInfo); 
    } 
); 

UiResultsItemInforParser是子類型稱爲EvntParsere超類型的明明是事件對象。

EvntParser看起來是這樣的:

function EvntParser (e) { 
    this._evntInfo = {}; 
    this._evntInfo.time = e.timeStamp.toString(); 
    this._evntInfo.type = 'event'; 
} 

EvntParser.prototype = { 
    set evntInfo(e) { 
     this._evntInfo.time = e.timeStamp.toString(); 
     this._evntInfo.type = 'event'; 
    }, 
    get evntInfo() { 
     return JSON.stringify(this._evntInfo); 
    } 
}; 

UiResultsItemInforParserEvntParser衍生,看起來像這樣:

function UiResultsItemInfoParser(e) { 
    EvntParser.call(this, e); 
} 

UiResultsItemInfoParser.prototype = new EvntParser(); 
UiResultsItemInfoParser.prototype.constructor = UiResultsItemInfoParser; 

不幸的是,我得到TypeError: e is undefinedEvntParserthis._evntInfo.time = e.timeStamp.toString();在觸發事件和在addEventListener中創建新的UiResultsItemInfoParser對象。

爲什麼會這樣,我怎樣才能修復它在EvntParser訪問事件對象的過程中創建對象?

回答

1

UiResultsItemInfoParser.prototype = new EvntParser(); 

是一個選擇重複反模式,和你的問題的根源。 EvntParser需要一個參數,並假定它被給出(this._evntInfo.time = e.timeStamp.toString()),所以當你這樣做時失敗。

相反:

UiResultsItemInfoParser.prototype = Object.create(EvntParser.prototype); 

這將創建具有EvntParser.prototype作爲其原型對象,但沒有調用EvntParser。 (然後你的下一行就是正確的,修復constructor生成的對象。)

後來,你在子類構造函數中做EvntParser.call(this, e);做正確的事情。所以這只是一條線。


由於您使用的是箭頭功能,因此您必須在ES2015環境中工作。這意味着你可以使用新的class語法,做這一切繁瑣的事情掛鉤爲你:

class EvntParser { 
    constructor(e) { 
     this._evntInfo = {}; 
     this._evntInfo.time = e.timeStamp.toString(); 
     this._evntInfo.type = 'event'; 
    } 
    set evntInfo(e) { 
     this._evntInfo.time = e.timeStamp.toString(); 
     this._evntInfo.type = 'event'; 
    } 
    get evntInfo() { 
     return JSON.stringify(this._evntInfo); 
    } 
} 

class UiResultsItemInfoParser extends EvntParser { 
} 

注意如何你甚至都不需要UiResultsItemInfoParser定義構造函數;當你不這樣做時,JavaScript引擎會爲你定義一個叫它super的所有參數。


邊注:本:

this._evntInfo = {}; 
this._evntInfo.time = e.timeStamp.toString(); 
this._evntInfo.type = 'event'; 

也可以寫成

this._evntInfo = { 
    time: e.timeStamp.toString(), 
    type: 'event' 
}; 
如果你喜歡

(甚至ES2015之前)。完全相同的對象被創建。

+0

謝謝!非常有趣,我從一本全新的參考書和初學者書中獲得了模式(https://www.amazon.de/JavaScript-Fortgeschrittene-Objektorientierung-funktionale-Programmierung/dp/3836238381)。這真是一個恥辱。 (注意:我使用僞類符號只是爲了得到一種我不太瞭解的原型邏輯的感覺,但無論如何thx!) –

+1

@CutúChiqueño:哦,那**是一種遺憾。如果這本書有一個網站,也許你可以報告一個錯誤......呃,正如我所說的,其他一切都是正確的。 :-) –

相關問題