Pam*_*Pam 5 javascript oop jquery
我刚刚开始使用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
}
});
},
listenForInput : function(theField) {
// theField.keyup(function() {
// if ($(this).val().length > 0) {
// theField.removeClass('invalid');
// }
// });
alert('I work!!!!');
}
} // end obj
Run Code Online (Sandbox Code Playgroud)
正如我在评论中所说,你必须在函数内部保留一个引用:
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));
}
});
},
Run Code Online (Sandbox Code Playgroud)
你正在传递一个函数each.在这个回调中,this引用了DOM元素.这就是为什么你将它传递给jQuery($(this))以便能够在该元素上调用jQuery方法.它也不能参考formObj!
什么this是指由下式确定如何一个函数被调用,并且每个功能都有自己的this(在Mozilla的机制的文档描述this更详细).
如果你打电话validate跟formObj.validate(),然后this指formObj.
状态的jQuery 文档each:
更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字
this引用该元素.