如何从Javascript中的内部函数访问父对象?

时间:2015-07-02 16:30:42

标签: javascript events methods scope this

我已按以下方式宣布课程:

function maskEditor() {
    this.init();
};

maskEditor.prototype = {
    foo: null,
    container: new createjs.Container(),

    init:function () {
        this.foo = "bar";
        this.container.on("mousedown", this.onMouseDown); // This is just an easeljs event dispatcher
    },

    onMouseDown: function (event) {
        alert(this.foo); // WRONG. 'this' is out of the scope :(
    }
};

长话短说:我使用的是easeljs库,我已经宣布了一个事件调度程序来捕获鼠标点击。我需要从该方法内部访问maskEditor对象。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您需要将上下文绑定到eventhandler:

this.container.on("mousedown", this.onMouseDown.bind(this));