![](/img/trans.png)
[英]Javascript - How to call a method in another method within the same class
[英]How to call a method from another method within the same object in JavaScript?
我剛剛開始使用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的機制的文檔描述了this
更詳細)。
如果使用formObj.validate()
調用validate
,那么this
引用formObj
。
更重要的是,回調是在當前DOM元素的上下文中觸發的,因此關鍵字
this
指的是元素。
我錯過了什么,或者你不能只是按名稱引用對象,如下所示:
var myObj = {
foo: function() {
alert('hello');
myObj.bar();
},
bar: function() {
alert('world');
}
}
myObj.foo();
函數的this關鍵字由調用設置,在函數執行期間不能更改。
調用obj.foo()
設置FOO的這 OBJ所以調用this.bar調用obj.bar。 但是,如果你以其他方式調用foo ,例如:
var a = obj.foo;
a();
那么它這將可能獲得obj(在上述情況下,將在嚴格模式窗口或不確定的 ),所以如果這個對象沒有酒吧屬性,你得到一個不同的酒吧或錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.