对象数组中的函数对象

问题描述 投票:1回答:1

我正在尝试以面向对象的方式在Javascript中实现模型。假设我的对象X具有一堆函数。我想有一个对象数组“在X中”,它的某些字段指向X中的某些函数。这是我尝试过的示例:

function X(){

this.open = function(e){...};
this.run = function(e){...};
this.close = function(e){...};
//...

this.STATES = {
    1: {name : "opening", applyAction : this.open},
    2: {name : "runing", applyAction : this.run},
    3: {name : "closing", applyAction : this.close},
    //...
};

this.currentState = this.STATES[1];

//...

this.update = function(e){
    //...
    currentState.applyAction(e);
    //...
}

但是这种方法无法按预期工作。我无法弄清楚哪里出了问题,如果您有另一种做同一件事的方式,我将不胜感激。

javascript arrays function-pointers dom-events
1个回答
1
投票

这不起作用,因为以下代码中的“ this”指向您正在定义的文字对象,而不是预期的“ this”:

this.STATES = {
    1: {name : "opening", applyAction : this.open},
    2: {name : "runing", applyAction : this.run},
    3: {name : "closing", applyAction : this.close},
    //...
};

尝试

function X() {
    var self = this;

    this.open = function() {
        // ...
    }

    this.STATES = {
        1: {name: "opening", applyAction: self.open},
        ...

我还将阅读有关Javascript范围的信息。

© www.soinside.com 2019 - 2024. All rights reserved.