-1

I'm just trying to figure out how I can call a javascript object method from within a method of the same object as below..

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

    },

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

Changed my question as I realise when using this.method2() it is refering to the WebSocker object.

Dairo
  • 822
  • 1
  • 9
  • 22
Jack
  • 417
  • 2
  • 8
  • 18

3 Answers3

4

There are a lot of answers in SO for problems like this, you should do a little research(on SO or on Google) before asking here.

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
    }
}

You need to reference to the current object using this, otherwise the JS Engine will look for a function named method1 in any of the higher scopes, all the way up to the global namespace. If such a function object (or such a name doesn't exist), method1 will be evaluated to undefined.

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
1

try this

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

        },

        method2: function() {
            testObject.method1();
        }
    }
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
0

updated to match your current question: good part is you can add additional functions and call any one of them with this method;

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']();
}
}
jidexl21
  • 609
  • 7
  • 22