[英]How can I have setTimeout execute a method in an object?
我想在短暫的延遲后,通過mouseleave事件關閉下拉菜單。 但是我很難讓它工作。
考慮對象中的以下方法:(我正在使用jQuery)
myObj = {};
myObj.message = "woot!";
myObj.bindEvents = function() {
var that = this;
$("#menuPanel")
.bind("mouseleave", function() {
that.timer = setTimeout(that.closeMenu,500);
});
}
myObj.closeMenu = function() {
// close the menu
alert(this.message);
}
這行不通。 也就是說,this.message出現未定義。 經過一番挖掘,我明白了為什么。 :)'that'引用在執行時不適用於setTimeout內部的代碼。
我想知道,解決此類問題的“最佳”方法是什么? 如何使用setTimeout的方法在同一對象中調用另一個方法,並且仍然可以訪問該對象中的屬性?
在此先感謝您的幫助。
這里的問題是您要從其對象分離closeMenu方法。 如果這樣做,您將遇到同樣的問題:
var closeMenu = myObj.closeMenu; // detaching the method from the object
closeMenu();
這樣的分離和調用方法意味着它們不再適用於在其上創建的對象。 在您的示例中,您正在做幾乎相同的事情:
// Setting the first parameter of setTimeout to be the detached closeMenu method
that.timer = setTimeout(that.closeMenu,500);
第一種方法的解決方法是使用call
或apply
方法:
var closeMenu = myObj.closeMenu; // detaching the method from the object
closeMenu.apply(myObj);
但這對於計時器不起作用。 而是創建一個匿名函數:
that.timer = setTimeout(function () { that.closeMenu(); },500);
bind()
-不要與jQuery的$('#selector').bind()
混淆-這種方法在各種博客和某些庫中都經常出現(原型是最著名的)現在,終於在ECMAScript第5版中實現了。
that.timer = setTimeout(that.closeMenu.bind(that),500);
我在創建的一兩個類中使用了類似的方法,因為它使事情變得更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.