【发布时间】:2012-09-03 15:19:15
【问题描述】:
上下文
当我使用 jQuery 时,我经常需要将this 保存在一个变量中:
var obj = {
myVar: null,
myFunction1: function() { ... },
myFunction2: function() {
this.myVar = "blabla";
this.myFunction1();
var ctx = this;
$('xxx').click(function () {
ctx.myFunction1();
});
}
}
在这种情况下,我将所有 this 替换为我的变量:
var obj = {
myVar: null,
myFunction1: function() { ... },
myFunction2: function() {
var ctx = this;
ctx.myVar = "blabla";
ctx.myFunction1();
$('xxx').click(function () {
ctx.myFunction1();
});
//etc. I do it for all "this" even if I have 15 "this"...
}
}
问题
- 将
this保留在变量中是一种好习惯吗?还有其他方法吗? - 用变量替换所有
this是否是个好习惯?
【问题讨论】:
标签: javascript jquery coding-style this readability