如何从方法中调用JavaScript对象方法

时间:2013-08-02 09:31:08

标签: javascript

我只想弄清楚如何在同一个对象的方法中调用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对象。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

试试这个

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

        },

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

答案 2 :(得分: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']();
}
}
相关问题