我刚刚开始使用 OO javascript,所以请多多包涵。
这个有效:
var myObj = {
foo : function() {
alert('hello');
this.bar();
},
bar: function() {
alert('world');
}
}
但是,如果我在“foo”方法中的 hello 警报之后做了一些其他事情,那么“this”的含义将从对象变为我上次选择的任何内容,因此使用 this.bar()
不执行类中的其他方法。
所以我尝试将“this”缓存在一个变量中,如下所示:
var myObj = {
publicVars: {
theObj : this
},
foo : function() {
alert('hello');
publicVars.theObj.bar();
},
bar: function() {
alert('world');
}
}
但这也没有用。那么解决方案是什么?
编辑
这是我的实际代码:
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
}
});
},
listenForInput : function(theField) {
// theField.keyup(function() {
// if ($(this).val().length > 0) {
// theField.removeClass('invalid');
// }
// });
alert('I work!!!!');
}
} // end obj
最佳答案
正如我在评论中所说,您必须在函数内部保留一个引用:
validate: function(theForm) {
var self = this;
$('input, textarea', theForm).each(function() {
var valueLength = $(this).val().length;
if (valueLength === 0) {
$(this).addClass('invalid');
self.listenForInput($(this));
}
});
},
您正在将一个函数传递给each
。在此回调中,this
引用 DOM 元素。这就是将它传递给 jQuery ($(this)
) 以便能够对该元素调用 jQuery 方法的原因。它也不能引用 formObj
!
this
指的是什么 如何 函数被调用,每个函数都有自己的 this
(Mozilla documention 描述 this
更详细)。
如果您使用 formObj.validate()
调用 validate
,则 this
引用 formObj
。
jQuery documentation for each
状态:
More importantly, the callback is fired in the context of the current DOM element, so the keyword
this
refers to the element.
关于javascript - 如何从 JavaScript 中同一对象中的另一个方法调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155227/