Using this inside an Javascript IIFE within an object

2.2k views Asked by At

I would like to use this instead of the name of the object inside the IIFE.

var ops = {
   start: (function (){
      socket.on('set', function(data) { 
         ops.getData();             
    });
  }()),
  getData: function (){
      ... 
  }
};

How it can be done?

3

There are 3 answers

0
Igor On

You cannot. Not to mention that your function does not return anything to assign to ops.start.

var ops = {
  start: function (){
    var self = this;
    socket.on('set', function(data) { 
      self.getData();             
    });
  }
};

ops.start();
0
Peter Chon On

You can create a new object and use it's prototype to access "this":

var o = Object.create(Object.prototype, {
  data: {
    value: 12
  },
  getobject: {
    get: function() {
      return this.data;
    }
  }
});

o.getobject;
0
Gennadiii On

You could use getter and closure on your function context if needed. Getter automatically invokes a function:

var ops = {
   get start() {
      return socket.on('set', function(data) { 
         ops.getData();             
    });
  },
  getData: function (){
  }
};

Now you can just refer to ops.start