如何从 Javascript 中的内部函数访问父对象?
How can I access the parent object from an inner function in Javascript?
我已经通过以下方式声明了一个 class:
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 对象。我该怎么做?
您需要将上下文绑定到事件处理程序:
this.container.on("mousedown", this.onMouseDown.bind(this));
我已经通过以下方式声明了一个 class:
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 对象。我该怎么做?
您需要将上下文绑定到事件处理程序:
this.container.on("mousedown", this.onMouseDown.bind(this));