对象数组中的函数对象

发布于 2024-11-15 20:41:24 字数 611 浏览 3 评论 0原文

我正在尝试以面向对象的方式在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舟遥客 2024-11-22 20:41:24

这不起作用,因为以下代码中的“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 范围的内容。

This won't work because 'this' inside of the following code points to the literal object you're defining, not the intended 'this':

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

Try

function X() {
    var self = this;

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

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

I'd also read up about Javascript scoping.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文