我刚刚开始使用OO javascript,所以请耐心等待.
这有效:
var myObj = {
foo : function() {
alert('hello');
this.bar();
},
bar: function() {
alert('world');
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我在"foo"方法中的hello警告之后执行其他操作,则"this"的含义会从对象更改为我上次选择的任何内容,因此使用this.bar()不会执行类中的其他方法.
所以我试着在这样的变量中缓存"this":
var myObj = {
publicVars: {
theObj : this
},
foo : function() {
alert('hello');
publicVars.theObj.bar();
},
bar: function() {
alert('world');
}
}
Run Code Online (Sandbox Code Playgroud)
但这也不起作用.那么解决方案是什么?
这是我的实际代码:
var formObj = {
validate : function(theForm) {
$('input, textarea', theForm).each(function() {
var valueLength = $(this).val().length;
if (valueLength === 0) {
$(this).addClass('invalid');
this.listenForInput($(this)); // <!------- this isn't working
}
}); …Run Code Online (Sandbox Code Playgroud)