2011-06-18 136 views
1

我想以面向对象的方式在JavaScript中实现一个模型。假设我有一堆功能的对象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); 
    //... 
} 

但是预期这种方法是行不通的。我无法弄清楚什么是错的,如果你有另一种做同样的事情的方式,我会很感激。

回答

1

,因为“这个”下面的代码指向文本对象的内部你定义,而不是预期的“这个”这是行不通的:

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范围的内容。

+0

非常感谢!这是一个很好的帮助 – user804723

+0

我已经写了一个关于同一点的教程。 'this'指针的行为在这里解释:https://rahuldotout.wordpress.com/2011/05/21/professional-javascript-part-6-objects-without-classes/2/ – rahulmohan