コンテキストとして 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 がコンテキストを保持します。クリック イベントは、引数をスローして渡されます。