javascript - 如何在 Javascript 中的不同对象之间调用方法?

标签 javascript

我正在使用 DHTMLX-touch 框架(基本上是 javascript)为移动设备开发应用程序。

我有一个实现此功能的 A 类:

A.prototype.initEventHandler = function(controller) {
    $$('btn_submit').attachEvent('onItemClick', controller.switchView($$('ui_ewmon_main')));
}

第一次实现

对象 Controller 是B类的一个实例,B类如下:

function B() {     
    //back button management
    this.last_view=new Array();
    this.current_view=this.ewmon_view.getRoot();

    this.switchView = function(next) {
        this.last_view[this.last_view.length]=this.current_view;
        this.current_view=next;
        next.show();
    }
}

使用 Firebug 我得到这个错误:

A.js:32Uncaught TypeError: Object # has no method 'switchView'

二次实现

如果我尝试将 switchView 函数定义为原型(prototype)函数:

function B() {     
    //back button management
    this.last_view=new Array();
    this.current_view=this.ewmon_view.getRoot();
}
B.prototype.switchView = function(next) {
    this.last_view[this.last_view.length]=this.current_view;
    this.current_view=next;
    next.show();
}

在这种情况下,我得到以下错误:

B.js:13Uncaught TypeError: Cannot read property 'length' of undefined

谁能帮帮我?

提前致谢 达尼洛

最佳答案

您正在调用 attachEvent 并返回 controller.switchView($$('ui_ewmon_main')),以获得您想要的结果:

A.prototype.initEventHandler = function(controller) {
    $$('btn_submit').attachEvent('onItemClick', function(){ controller.switchView($$('ui_ewmon_main')); });
}

编辑:

查看您发布的代码,我预计会出现此错误。从 this.current_view=this.ewmon_view.getRoot(); 行,我们会猜测 this.current_view 始终是一个对象,类似于 EWmonView.prototype 返回的对象.getRoot(正确?),但此对象没有方法 show

但是您调用 controller.switchView($$('ui_ewmon_main')); 导致 this.current_view 成为 $$('ui_ewmon_main' ),在数组this.last_viewthis.current_view中保留不同的对象类型是错误的根源。

肮脏的修复将是:

if (this.current_view.show) {
    this.current_view.show();
} else{
    $$('ui_ewmon_main').show(); //or $$('ui_ewmon_login').show() can tell what you want =)
}

在 EWmonController 中出现 this.current_view.show(); 的地方。但是重写代码并让 this.current_view 始终具有相同类型的对象对我来说看起来更好。

关于javascript - 如何在 Javascript 中的不同对象之间调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7836714/

相关文章:

javascript - 将鼠标悬停在特定导航链接上时如何使用不同的 Logo 交换页面 Logo

javascript - 通过ajax在rails中显示警报消息

javascript - 在 HTML5 中使用drawImage

javascript - 使用ajax请求更改浏览器url而不重新加载页面

javascript - 使用 on{X} api 获取设备的当前位置

Javascript else 换行

javascript - Php - Javascript - 我如何知道哪些页面是彩色的,哪些是黑白的?

javascript - 使用 JavaScript,为什么我的 onmouseover 事件没有被触发?

javascript - Angularjs - 在 Controller 之间共享数据

javascript - 如何获取 jquery datepicker 的所有选项以使用相同的选项实例化新的 datepicker?