对象数组中的函数对象
我正在尝试以面向对象的方式在 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);
//...
}
但是,这种方法不能按预期工作。我不知道出了什么问题,如果您有其他方法做同样的事情,我将非常感激。
I am trying to implement a model in Javascript in a object-oriented manner. Say I have object X with bunch of functions. I want to have an object array "in X" that some of its fields point to some functions in X. Here is the example of what I tried:
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);
//...
}
However this approach does not work as expected. I cant figure out what is wrong, also if you have alternative way of doing the same thing I would truly appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不起作用,因为以下代码中的“this”指向您正在定义的文字对象,而不是预期的“this”:
尝试
我还阅读了有关 Javascript 范围的内容。
This won't work because 'this' inside of the following code points to the literal object you're defining, not the intended 'this':
Try
I'd also read up about Javascript scoping.