Javascript 变量访问原型

Javascript 变量访问原型,javascript,prototypejs,dom-events,webos,mojo-sdk,Javascript,Prototypejs,Dom Events,Webos,Mojo Sdk,我正在开发新的Palm Pre WebOS,Palm Pre的应用程序是在MojoSDK中开发的,MojoSDK是在原型Javascript框架之上开发的 我试图访问事件处理程序中助手级别定义的变量,这些变量也是同一助手的一部分。当我访问事件处理程序中的助手级别变量时,我将其视为未定义。但是,可以在设置功能中访问变量 请查看以下代码以供参考: 代码: 我在这里称之为: Mojo.Event.listen(this.myTestList, Mojo.Event.listTap, this.test

我正在开发新的Palm Pre WebOS,Palm Pre的应用程序是在MojoSDK中开发的,MojoSDK是在原型Javascript框架之上开发的

我试图访问事件处理程序中助手级别定义的变量,这些变量也是同一助手的一部分。当我访问事件处理程序中的助手级别变量时,我将其视为未定义。但是,可以在设置功能中访问变量

请查看以下代码以供参考:

代码:

我在这里称之为:

Mojo.Event.listen(this.myTestList, Mojo.Event.listTap, this.testListTapHandler); 

还有谁有这个问题,或者我做错了什么?可以访问处理程序中的变量吗?或者我们可以考虑解决方法来实现它吗?

我不熟悉mojo sdk,但这听起来很像您在设置事件处理程序时混淆了“this”引用。很可能,当调用testListTapHandler时,它会引用触发事件的对象

Prototype有非常方便的方法来帮助消除这种混乱

我猜你有过这样的经历

elem.observe('eventname', myTestAssistant.testListTapHandler);
问题是,当触发事件时,在testListTapHandler内部,这将引用元素。要更正此问题,我们将事件处理程序与所需对象绑定:

elem.observe('eventname', myTestAssistant.testListTapHandler.bind(myTestAssistant));

我已经找到了这个问题的解决办法。我也是

正如保罗所指出的,核心问题具有约束力和范围

为了使其正常工作,我将我的实现更新为以下内容:

function MyTestAssistant(passedValue)
{
    this.passedValue = passedValue;
}

MyTestAssistant.prototype.setup = function()
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor

    // Was Using the following code before and this.passedValue wasn't accessible in 
    // testListTapHandler

    // Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);

    // Used the following code now and this.passedValue is accessible in 
    // testListTapHandler

    this.testListTapHandler = this.testListTapHandler.bindAsEventListener(this);
    Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);  
}

MyTestAssistant.prototype.testListTapHandler = function(event)
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor
}
谢谢你的帮助,保罗

问候,

穆罕默德·哈塞布·汗

function MyTestAssistant(passedValue)
{
    this.passedValue = passedValue;
}

MyTestAssistant.prototype.setup = function()
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor

    // Was Using the following code before and this.passedValue wasn't accessible in 
    // testListTapHandler

    // Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);

    // Used the following code now and this.passedValue is accessible in 
    // testListTapHandler

    this.testListTapHandler = this.testListTapHandler.bindAsEventListener(this);
    Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);  
}

MyTestAssistant.prototype.testListTapHandler = function(event)
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor
}