-1

我只是想弄清楚如何从以下同一对象的方法中调用 javascript 对象方法。

var testObject = {
    method1 : function() {
        var connectionAddr = "ws://localhost:8003";
        socket = new WebSocket(connectionAddr);
        socket.onmessage = function(event) {
            method2();
        }

    },

    method2: function() {
        this.method1();
    }
}

改变了我的问题,因为我在使用 this.method2() 时意识到它指的是 WebSocker 对象。

4

3 回答 3

4

SO中有很多针对此类问题的答案,您应该在此处提问之前进行一些研究(关于SO或Google)。

var testObject = {
    method1 : function() {
        var connectionAddr = "ws://localhost:8003",
            self = this;
        socket = new WebSocket(connectionAddr);
        socket.onmessage = function(event) {
            self.method2();
        }
    },

    method2: function() {
        this.method1(); //something like this would cause an infinite call stack, you should change this code
        //this refers to the current object, so has properties method2 and method2
    }
}

您需要使用 引用当前对象this,否则 JS 引擎将查找method1在任何更高范围内命名的函数,一直到全局命名空间。如果这样的函数对象(或这样的名称不存在),method1将被评估为undefined.

于 2013-08-02T09:32:42.483 回答
1

尝试这个

var testObject = {
        method1 : function() {
            var connectionAddr = "ws://localhost:8003";
            socket = new WebSocket(connectionAddr);
            socket.onmessage = function(event) {
                testObject.method2();
            }

        },

        method2: function() {
            testObject.method1();
        }
    }
于 2013-08-02T09:50:22.650 回答
0

更新以匹配您当前的问题:好的部分是您可以添加其他功能并使用此方法调用其中任何一个;

var testObject = {
   method1 : function() {
    var connectionAddr = "ws://localhost:8003",
        self = this;
    socket = new WebSocket(connectionAddr);
    socket.onmessage = function(event) {
        self['method2']();
    }
},

method2: function() {
    this['method1']();
}
}
于 2013-08-02T09:47:53.973 回答