0

In my Chrome App I need somehow Chrome to give the the reference to my object 'identity_service' in this variable when the callback is executed, but I don't know how.

This is my constructor:

function Identity(identity_host,identity_port) {

    this.identity_host=identity_host;
    this.identity_port=identity_port;
    this.socket_fd=0;

    chrome.sockets.tcp.create({}, this.socket_create_callback);

}

The function socket_create_callback is defined like this:

Identity.prototype.socket_create_callback=function(info) {
    console.log('info='+info);
    console.log('constructor name:'+this.constructor.name);
    console.log('hostname='+this.identity_host);
    this.socket_fd=info.socketId;
}

This is how I create it:

var identity_service=new Identity("localhost",4433);

Without object oriented programming Chrome calls the callback function with the parameter 'info' and it works fine. But when using OOP the 'this' variable doesn't hold the reference to my 'Identity' object otherwise the 'hostname' would not be undefined. This is what I get in the console log:

identity.js:21 info=[object Object]
identity.js:22 constructor name:Object
identity.js:23 hostname=undefined

With correct invocation of the callback the name of the csontructor would be 'Identity'. How can this be fixed?

The Chrome API call for creating a socket is this:

create

chrome.sockets.tcp.create( SocketProperties properties, function callback)

Creates a TCP socket.

Nulik
  • 6,748
  • 10
  • 60
  • 129
  • Well, of course. You should bind the actual object: `chrome.sockets.tcp.create({}, this.socket_create_callback.bind(this));`. There's no way the other function would know which `this` to use. – wOxxOm Aug 07 '16 at 17:13
  • A detailed answer: [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/a/20279485) – wOxxOm Aug 07 '16 at 17:15
  • There are hundreds of duplicates of this type of question here. – jfriend00 Aug 07 '16 at 17:18
  • @wOxxOm but how do you pass the "info" parameter which Chrome should return ? – Nulik Aug 07 '16 at 17:30
  • Maybe that answer I've linked is not the best, but you can (and should) read in the documentation for `bind`: in short, when it is used with only one parameter it redefines only `this`, all conventional parameters will be passed as is. There are other methods (faster) than `bind`, see that answer for examples or find a better one, there are lots. – wOxxOm Aug 07 '16 at 17:39

0 Answers0