[英]javascript object, seeing expected result using two different ways of calling function
我不明白為什么會這樣......
我需要獲取在mousedown上設置的對象startPoint
和來自mousemove的當前e.pageY
來進行一些計算。
var adjustHeight = {
change: function(e) {
console.log(this.startPoint)
console.log(e.pageY);
},
};
$('#dragger').mousedown(function(e) {
e.preventDefault();
adjustHeight.startPoint = e.pageY;
$(window).on('mousemove', adjustHeight.change());
$(window).on('mouseup', function() {
$(window).off('mousemove', adjustHeight.change())
});
})
然而,控制台打印出對象startPoint
,這是我所期望的,但e.pageY
是未定義的
但是當我使用這條線時
...
$(window).on('mousemove', adjustHeight.change);
$(window).on('mouseup', function() {
$(window).off('mousemove', adjustHeight.change)
});
...
我按預期獲得了e.pageY
,但現在startPoint
未定義。 當我檢查this
是指向它的是DOMWindow ....
我的問題是為什么會發生這種情況,我將如何同時獲取對象屬性和函數e
?
$(window).on('mousemove', adjustHeight.change());
正在執行adjustHeight.change
並將返回值傳遞給.on()
。 由於您沒有將任何參數傳遞給adjustHeight.change
,因此e
將是undefined
(並且e.pageY
將不可用)。
$(window).on('mousemove', adjustHeight.change);
正確地將函數傳遞給.on
,因此稍后將事件對象傳遞給處理程序,您可以訪問e.pageY
。 但是上下文( this
)不再是adjustHeight
,它是綁定處理程序的DOM元素。 在這種情況下哪個是window
, window
沒有startPoint
屬性。
所述MDN文檔具有約一個很好的文章this
(一般), 一樣quirksmode.org (相對於事件處理程序)。
方案 :
將一個新函數作為處理程序傳遞,調用adjustHeight.change
並傳遞event
對象:
$(window).on('mousemove', function(event) {
adjustHeight.change(event);
});
或使用$.proxy
[docs] 將 adjustHeight.change
綁定到adjustHeight
:
$(window).on('mousemove', $.proxy(adjustHeight.change, adjustHeight));
由於您以后還想要解除處理程序的綁定,您應該將其分配給變量或使用命名空間事件[docs] 。
例:
$(window).on('mousemove.dragger', $.proxy(adjustHeight.change, adjustHeight));
$(window).on('mouseup.dragger', function() {
// removes both, the mousemove and mousup event handlers
$(window).off('.dragger');
});
首先,這是錯誤的:
$(window).on('mousemove', adjustHeight.change());
然后,默認情況下, change()
不綁定adjustHeight
。 你必須做的事情如下:
$(window).on('mousemove', function() {
adjustHeight.change();
});
或者,在現代瀏覽器中:
$(window).on('mousemove', adjustHeight.change.bind(adjustHeight));
...
$(window).on('mousemove', adjustHeight.change);
$(window).on('mouseup', function() {
$(window).off('mousemove', adjustHeight.change)
});
...
(行:3)
console.log("start:" + adjustHeight.startPoint)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.