对于您的画布使用 Box 实例作为它的上下文,您需要绑定它。
你可以尝试这样的事情:
function Box( boxData ) {
// References the Box instance as I want.
console.log( this );
// I need to access this later...
var boxName = boxData.name;
// public property boxName
this.boxName = boxName;
var $canvas = $( '#rm-' + boxData.id ).find( 'canvas' );
$canvas.on( 'mousedown', this.onMouseDownHandler.bind(this) );
// ----------------------------------------------^
// this bind will prevent the event use canvas element as context
}
function Room() {
// some stuff
}
Room.prototype = new Box({name: 'this will always be my rooms box'});
Room.prototype.onMouseClickHandler = function( event ) {
// 'boxName' is undefined as 'this' references 'event.target'
console.log( this.boxName );
}
现在你可以试试这个:
var foo = new Room();
foo.onMouseClickHandler();
您的控制台将记录this will always be my rooms box
.
你要记住 Room 扩展了 Box 的一个实例,所以如果你这样做:
foo.boxName = 'my name is what?!';
// you changed the this so the prototype will get the new value:
foo.onMouseClickHandler(); // 'my name is what?!'
编辑(问题升级后)
只需this.boxName
使用var boxName
:
function Box( boxData ) {
// References the Box instance as I want.
console.log( this );
// public property boxName
this.boxName = boxName;
}
如果你想为其他对象添加一个 EventHandler 但保留你的 Box 上下文,你需要这样做:
var foo = newBox({boxName: 'foo'});
var bar = document.queryElementById('bar');
bar.addEventHandler('click', foo.onMouseClickHandler.bind(foo));
现在,如果您单击bar
元素,来自 foo 的 onMouseClickHandler 将保持它的上下文。click 事件将通过 throw 参数传递。