Max*_*ich 0 javascript jquery scope this
在很多情况下,我已经看到了jQuery如何修改this关键字以提供您期望实际存在的对象的伟大之处.大....
但是,您如何处理具有自定义对象的情况,该自定义对象具有引用此关键字但通过jQuery调用的自定义方法.
例如:
var myCustomObject = {
myCustomValue: 1,
myCustomMethod: function () {
switch (this.myCustomValue) {
case ....
}
}
};
Run Code Online (Sandbox Code Playgroud)
如果使用jQuery回调调用"this"现在是jQuery"context",显然会为myCustomValue返回undefined.
我注意到我可以直接引用实例,例如
switch (myCustomObject.myCustomValue) {}
Run Code Online (Sandbox Code Playgroud)
但这似乎令人烦恼地冗长,我想知道是否有任何意想不到的副作用可能由此造成...
这种情况的最佳做法是什么?
如果不必公开:
var myCustomObject = new (function()
{
var myCustomValue = 1;
this.myCustomMethod = function () {
switch (myCustomValue) {
}
}
})();
Run Code Online (Sandbox Code Playgroud)
如果是这样的话:
var myCustomObject = new (function()
{
this.myCustomValue = 1;
var self = this;
this.myCustomMethod = function () {
switch (self.myCustomValue) {
}
}
})();
Run Code Online (Sandbox Code Playgroud)
self 可以随心所欲地调用.