从充当事件处理程序的多个方法中引用对象 属性

referencing object property from multiple methods that act as eventhandlers

我正在重新设计一个旧脚本,首先使其成为 OOP,然后再使用 jQuery。我知道之前有人问过这个问题,但答案似乎不适合我的情况。或者我不明白 jQuery 知识。

此工作脚本根据鼠标事件调整 DIV 的大小,在它们之间传递布尔值 属性。但是这些方法通过对象名称引用属性,这是我理解的糟糕的 OOP。 我看到很多关于 "init" 函数和重命名 "this" 的答案,但我无法将这些解决方案与我的脚本联系起来:

See my Fiddle.

PositionXY = {
    baseX : undefined,
    baseY : undefined,
    isRepositionable : true,

    detectBasePosition : function (e) {

        "use strict";
        PositionXY.isRepositionable = true;   // bad OOP
        e = e || window.event;    // crossbrowser event acces
        if (this.currentStyle){   // IE
            if (e.clientX || e.clientY) {
                PositionXY.baseX = e.clientX - this.currentStyle.width.replace(/px/,"");
                PositionXY.baseY = e.clientY - this.currentStyle.height.replace(/px/,"");   
            }
        } else if (window.getComputedStyle){  // Mozilla
            if (e.pageX || e.pageY) {
                PositionXY.baseX = e.pageX - document.defaultView.getComputedStyle(this,null).getPropertyValue("width").replace(/px/,"");
                PositionXY.baseY = e.pageY - document.defaultView.getComputedStyle(this,null).getPropertyValue("height").replace(/px/,"");
            }
        }
    },
    startPositionAdjustment : function (e) {

        "use strict";
        if (PositionXY.isRepositionable) {   // bad OOP
            e = e || window.event;           // crossbrowser event acces
            if (e.clientX || e.clientY) {    // IE
                this.style.width = e.clientX - PositionXY.baseX + "px";
                this.style.height = e.clientY - PositionXY.baseY + "px";
            } else if (e.pageX || e.pageY) {  // Mozilla 
                this.style.width = e.pageX - PositionXY.baseX + "px";
                this.style.height  = e.pageY - PositionXY.baseY + "px";
            }
        } else return;
    },
    stopPositionAdjustment : function () {

        "use strict";
        PositionXY.isRepositionable = false;    // bad OOP
    }
};


var elm = document.getElementById("x");
elm.onmousedown = PositionXY.detectBasePosition;
elm.onmousemove = PositionXY.startPositionAdjustment;
elm.onmouseup = PositionXY.stopPositionAdjustment;

您可以在函数中使用 this,但您必须确保正确 bind 事件处理程序:

 var elm = document.getElementById("x");
 elm.onmousedown = PositionXY.detectBasePosition.bind(PositionXY);
 elm.onmousemove = PositionXY.startPositionAdjustment.bind(PositionXY);
 elm.onmouseup = PositionXY.stopPositionAdjustment.bind(PositionXY);

然而,您在这里使用 this 获得的唯一优势是能够在更改 PositionXY 的初始值时将 PositionXY 重新别名到其他变量,这将可能永远不会发生。

使用 IIFE,您还可以克服该问题,同时保持初始设计的简单性:

var YourObject = (function () {
    var YourObject = {
        someProperty: 'test',
        someFunction: function () {
            console.log(YourObject.someProperty);
        }
    };

    return YourObject;
})();