在很多情况下,我都看到了 jQuery 如何修改 this 关键字以提供您希望实际存在的对象的伟大之处。太棒了....
但是,如果您的自定义对象具有引用 this 关键字但通过 jQuery 调用的自定义方法,您该如何处理这种情况。
例如:
var myCustomObject = {
myCustomValue: 1,
myCustomMethod: function () {
switch (this.myCustomValue) {
case ....
}
}
};
如果使用 jQuery 回调调用,“this”现在是 jQuery“上下文”,并且显然为 myCustomValue 返回未定义。
我注意到我可以直接引用实例,例如
switch (myCustomObject.myCustomValue) {}
但这似乎冗长得令人烦恼,我想知道这是否会导致任何意外的副作用......
此类场景的最佳实践是什么?
最佳答案
如果不必公开:
var myCustomObject = new (function()
{
var myCustomValue = 1;
this.myCustomMethod = function () {
switch (myCustomValue) {
}
}
})();
如果是:
var myCustomObject = new (function()
{
this.myCustomValue = 1;
var self = this;
this.myCustomMethod = function () {
switch (self.myCustomValue) {
}
}
})();
self
可以随意命名。
关于javascript - 自定义方法中的 jQuery 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201339/