this
참조 때문에 더 작은 방법으로 분해하려고 할 때 코드가 작동하는 데 문제가 있습니다. 내 코드는 다음과 같다 :함수 내에서 javacript에서 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
기술을 가능하면 사용하지 않도록합니다.
또한 pageObj
하고 무선으로 입력되는 참조 this
를 this
하는 참조를 참조 .bind()/.call()/.apply()
있어서 onChange()
하는 방법이 있는가?
필요에 따라 코드를 자유롭게 조정하십시오. 고마워, 앞으로! 아래의 코멘트에 @gyre에 의해 제안
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? : event.target
에
업데이트
덕분에 여기 아래에 제안 작업 코드 블록으로 this
을 제어하는 방법에 대한 훌륭한 세부 정보를 제공하지만은 언급하지 않습니다. 0. 어쨌든, 여기에 MDN Docs on Event.target
가능한 복제 [? 콜백 내에서 올바른 \ '이 \를'에 액세스하는 방법 (http://stackoverflow.com/questions/20279484/올바른 방법 -이 - 콜백 내부) – gyre