3
obj = {
  go: function() { alert(this) }
}

obj.go(); // object

(obj.go)(); // object

(a = obj.go)(); // window

(0 || obj.go)(); // window

Can anyone explain me why the latter two prints window object and the first two prints the reference.

1 Answer 1

6

When you execute a method directly, like the last two forms do, the this pointer is not set to the object. When not in strict mode, it is set to window (in strict mode, it would be set to undefined which helps you catch errors). The this pointer is set according to how you call something in javascript.

The simplest way to always make sure the this pointer is set accordingly is to always call the method in the context of an object like:

obj.go();

Here are some examples:

obj.method()    // this in method automatically set to obj

var a = obj.method();
a();            // this set to window as no object context is provided

var a = obj.method();
a.call(obj)     // this explicitly set to obj by .call()
a.apply(obj)    // this explicitly set to obj by .apply()

What you should remember is that obj.go is just a function in javascript that was originally stored as a property on obj. But, once you've gotten that property value, it is just a function pointer and no longer has any explicit association to any particular object. You have to give it an association to an object in how you call it if you want the this pointer set appropriately inside the method. This is different than in some other languages and like many things in JS that are different, it can be both a feature you can take advantage of and occasionally confusing to learn.

Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic... one final question... can you just explain me the object context part alone in brief... not getting it clearly.
@Kevin. Does my last paragraph not explain it? Once you've done a = obj.go, a is just a function pointer. It is not associated with any object. When you call a(), there is no object for the javascript engine to associate it with so it doesn't know what to do with the this pointer. In order to have the method associated with an object, you have to apply that association in how you call the method with one of the examples I've shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.