0

I am calling the following 3rd party JavaScript function:

var Socket = function(url) {
    sockets.push(this);
    var me = this;
    me.readyState = 0;
    window.setTimeout(function() {
        me.readyState = 1;
        me.onopen();
    }, 500);
};

via this:

connection = new Socket(socketURL);

Now I want to try and understand once and for all what it means to reference this inside a function. Is it the same as in Java. e.g. I am referring to myself or in the case of JavaScript I am referring to the namespace that the function resides in?

Whymarrh
  • 11,635
  • 13
  • 55
  • 96
juckky
  • 407
  • 3
  • 10

2 Answers2

3

The referece of this depends on how you are calling the function.

For example:

function globalFn() { return this.val; }

var objectA = { val: 1, localFn: globalFn };
var objectB = { val: 2, localFn: globalFn };

objectA.localFn(); // `this` will be `objectA`, so it returns `1`.
objectB.localFn(); // `this` will be `objectB`, so it returns `2`.

So far, so good. It looks like the same as in Java or other object oriented languages. But, this may seem tricky:

var myFn = objectA.localFn;
myFn(); // `this` will be `undefined` in strict mode, causing an error

This shows that this reference is not bound to the function itself, but to the way the function is called. You can "cheat" it by using call method of a function object:

myFn.call(objectA); // `this` will be `objectA`, returns `1`.
globalFn.call(objectB); // `this` will be `objectB`, returns `2`.
objectA.localFn.call(objectB); // `this` will be `objectB`, returns `2`.

You can even do this for objects that does not have the function defined as a property:

var objectC = {val: 3};
myFn.call(objectC); // `this` will be `objectC` and will return `3`.

It's quite hard to understand it at first, there's a great video that illustrates how it works at YouTube: The Definitive Guide to Object-Oriented JavaScript by James Shore.

Thiago Negri
  • 4,965
  • 2
  • 25
  • 38
0

Edited. Previous answer was not correct. Here's a good explanation:

code.tutsplus.com/tutorials/fully-understanding-the-codethiscode-keyword--net-21117

Oakley
  • 606
  • 10
  • 21