我有問題讓我的代碼工作,因爲我試圖將它分解成更小的方法,因爲this
引用。我的代碼如下:如何在函數內創建2`this`引用在函數內
const pageObject = {
/* set listener to get id of the radio input and then do something with it*/
onChange() {
// `this` here refers to the pageObject
console.log(this);
$('.radio input[type="radio"]').on('click', function() {
// `this` here refers to the radio input
console.log(this);
let $id = $(this).data('id');
// Error because `this` is referencing the radio input and not the pageObject.
this.doSomething($id);
}
},
/* just does something */
doSomething($id) {
return ...
}
}
// just calls the method on object so we can get started
pageObject.onChange();
我也想爲YDKJS: This & Object Prototypes建議避免使用ES6的箭頭功能() =>
和self = this
技術如果可能的話。
有一種方法來.bind()/.call()/.apply()
方法onChange()
引用this
,其引用到pageObj
,並且還向無線輸入this
,其引用?
如有必要,請隨意重新排列代碼。謝謝,期待!
更新
由於event.target
如下建議,這裏是工作的代碼塊:
const pageObject = {
/* set listener to get id of the radio input and then do something with it*/
onChange() {
// `this` here refers to the pageObject
console.log(this);
let radioHandler = function radioHandler(event) {
// `this` here also refers to the pageObject too since we are about to call this function via .bind()
console.log(this);
// use event.target here instead. sweet stuff.
let $id = $(event.target).data('id');
// doSomething() now works!
this.doSomething($id);
}
$('.radio input[type="radio"]').on('click', radioHandler.bind(this));
},
/* just does something */
doSomething($id) {
return ...
}
}
// just calls the method on object so we can get started
pageObject.onChange();
更新2
How to access the correct this
inside a callback?由@gyre在下面的意見建議提供瞭如何控制this
但未提及的詳細信息event.target
。無論如何,這裏是MDN Docs on Event.target
的可能的複製[?如何訪問正確的\'這\'回調內(http://stackoverflow.com/questions/20279484 /如何訪問正確的回調內部) – gyre