javascript对象,使用两种不同的函数调用方式查看预期结果

javascript对象,使用两种不同的函数调用方式查看预期结果,javascript,javascript-events,Javascript,Javascript Events,我不明白为什么会这样 我需要从mousemove中获取mousedown上设置的objectsstartPoint,以及当前的e.pageY,以进行一些计算 var adjustHeight = { change: function(e) { console.log(this.startPoint) console.log(e.pageY); }, }; $('#dragger').mousedown(function(e) { e.pr

我不明白为什么会这样

我需要从mousemove中获取mousedown上设置的objects
startPoint
,以及当前的
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
未定义。当我检查这个指向的是什么时,它是DOMWindow

我的问题是为什么会发生这种情况,以及如何同时获取对象属性和函数
e

$(window).on('mousemove', adjustHeight.change());
正在执行
adjustHeight.change
并立即将返回值传递给
.on()
。由于您没有将任何参数传递给
adjustHeight.change
e
未定义
(并且
e.pageY
将不可用)


将函数正确地传递给上的
,因此稍后事件对象将传递给处理程序,您可以访问
e.pageY
。但是上下文(
this
)不再是
adjustHeight
,而是将处理程序绑定到的DOM元素。在本例中,它是
window
,并且
window
没有
startPoint
属性

MDN文档(通常)有(关于事件处理程序)


解决方案

将新函数作为处理程序传递,该处理程序调用
adjustHeight.change
并传递
事件
对象:

$(window).on('mousemove', function(event) {
    adjustHeight.change(event);
});
或绑定
adjustHeight。使用以下命令将
更改为
adjustHeight

由于您还希望稍后解除绑定处理程序,因此应该将其分配给变量或使用

例如:

$(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));

(第3行)

$(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)
});
console.log("start:" + adjustHeight.startPoint)