gpt4 book ai didi

javascript - jQuery on Change 引用 this.value 和 this

转载 作者:行者123 更新时间:2023-11-28 05:32:18 24 4
gpt4 key购买 nike

假设我有一些这样的代码,它在选择更改时运行:

$('select[name="nights"]').on('change', function() {
console.log(this.value);
});

有什么方法可以引用我的全局 this 对象(如果它被称为那个)而不使用类似的东西:

var self = this;

使用诸如绑定(bind)之类的东西会破坏对 jQuery 选择元素的引用:

$('select[name="nights"]').on('change', function() {
console.log(this.value);
});

我不想更加简洁和理解范围,所以我更喜欢绑定(bind)而不是保存对此的引用。例如,如果我查看 Airbnb 的代码标准,他们也不会使用 self = this 引用。

https://github.com/airbnb/javascript#naming--self-this

我想知道他们如何解决类似的问题,尽管您都需要对 this 的本地范围引用和对全局对象的 this 引用。

我只是被迫仍然做出引用还是有什么办法解决这个问题?我可能只是在这里想得太多和吹毛求疵,但我希望有一个优雅的解决方案,否则我还不如一开始就坚持保存引用。

最佳答案

我不确定我是否理解你的问题。

使用#bind(ES5方式)

$('select[name="nights"]').on('change', function(){
console.log(this.value);
}.bind(this));

From https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

ES6方式

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Lexical this

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

An arrow function does not create its own this context; rather, it captures the this value of the enclosing context, so the following code works as expected.(I didn't copy the code)

所以,你可以使用箭头功能来实现它

$('select[name="nights"]').on('change', () => {
console.log(this.value);
});

关于javascript - jQuery on Change 引用 this.value 和 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39591562/

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