gpt4 book ai didi

JavaScript 变量作用域

转载 作者:行者123 更新时间:2023-11-29 22:17:33 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的应用程序,我将在其中创建一个 Box 对象的多个实例,这些实例将控制和操作它自己的数据。但是,我无法弄清楚如何创建全局变量以在每个单独的对象及其关联的原型(prototype)中使用...

例如,我试图引用它自己......

function Box( boxData ) {
// References the Box instance as I want.
console.log( this );

// I need to access this later...
var boxName = boxData.name;

var canvas = $( '#rm-' + boxData.id ).find( 'canvas' )[0];
$( canvas ).on( 'mousedown', this.onMouseDownHandler );
}

Box.prototype.onMouseClickHandler = function( event ) {
// 'boxName' is undefined as 'this' references 'event.target'
console.log( this.boxName );
}

请记住,它不能充当单例,因为我会在任何一个时间点拥有它的多个实例。

编辑:

我在构造函数中添加了事件监听器,更新了上面的代码。

最佳答案

为了让您的 Canvas 在上下文中使用 Box 实例,您需要绑定(bind)它。

你可以尝试这样的事情:

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 将保持它的上下文。点击事件将被传递并抛出参数。

关于JavaScript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14230002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com