gpt4 book ai didi

javascript - 如何从函数内在 javascript 中创建 2 `this` 引用

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:33 25 4
gpt4 key购买 nike

由于 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();

我还想尽可能避免使用 es6 的箭头函数 () =>self = this 技术,如 YDKJS: This & Object Prototypes 中所推荐的那样.

有没有办法通过.bind()/.call()/.apply()方法onChange()来引用this 哪个引用了 pageObj 以及 this 哪个引用了 radio 输入?

如有必要,请随意重新排列代码。谢谢,期待!

更新

感谢下面建议的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

最佳答案

您可以使用 event.targetevent.currentTarget 来引用元素事件被分派(dispatch)到的目标。 javascript 也缺少关闭 ).on() 调用。

$('.radio input[type="radio"]').on('click', function(event) {

// `this` here refers to the radio input
let $id = $(event.target).data('radioId');

// Error because `this` is referencing the radio input and not the pageObject.
this.doSomething($id);
})

关于javascript - 如何从函数内在 javascript 中创建 2 `this` 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42500055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com