1

Can someone explain the concept behind this ?

assume we have a function as a method of an object:

var myobj = {
    myfunc : function () {      
        console.log(this); // Logs reference to myobj.                            
    }
};
myobj.myfunc();

while a nested function inside the same function myfunc will return reference to head object ( window ) :

var myobj = {
    myfunc : function () {      
       ( function (){
           console.log(this); // Logs reference to head window object.   
       })();                     
    } 
 };
myobj.myfunc();

It really confuses me how this works, as i thought function will always return reference to the parent object.

The question is, is this a fixed rule, that is any nested function will always rreturn reference to window ?

ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
  • 1
    related: http://stackoverflow.com/questions/8670877/this-value-in-javascript-anonymous-function – alexp Aug 27 '14 at 14:24
  • your inner function is a closure, so "this" would always point to the window object.you have to save "this" on a temp variable before accessing it inside the anonymous function. – Prabhu Murthy Aug 27 '14 at 14:26
  • this might be a useful post for anyone who looks for deeper explaination : http://benalman.com/news/2010/11/immediately-invoked-function-expression/ , thanks to adeneo for the searching key IIFE. – ProllyGeek Aug 27 '14 at 14:38
  • Would you please post your code with usable indentation? – Bergi Aug 27 '14 at 16:08
  • @Bergi guess you have the privilge to edit my code , go ahead and fix it if you want , you are welcome. – ProllyGeek Aug 27 '14 at 16:14
  • @ProllyGeek: Yes, I have the *privilege* to edit it, but you as the poster have the *duty* to put readable code in your questions - it helps to get good answers and upvotes. – Bergi Aug 27 '14 at 16:17
  • @Bergi ok done , let me know if it requires further modifications. – ProllyGeek Aug 27 '14 at 16:22

2 Answers2

4

The value of this inside a function depends on how it's called, not how it's defined

When you call the function in the scope of myobj, myobj will be the value of this

myobj.myfunc();

When you call a function with no execution context, the value of this will be the global object, in this case window.

function test() {

    console.log(this); // window

}

test(); // global context

when you create an IIFE, the execution context is the window as no other context is set

( function (){
    console.log(this); // window
})();

Then there's apply, call and bind which would let you set another value of this for the called function.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Actually i know this already , but my question is clear , it is all about nested functions , will any nested function return reference to head object ? – ProllyGeek Aug 27 '14 at 14:27
  • 1
    It's not about nested functions, how the function is defined is not what's important, it's how it's called. An IIFE is called right away with no special context, so it uses the global context, hence `this` inside the function is the window. – adeneo Aug 27 '14 at 14:28
  • IIFE umm , after searching i got it , thanks for the expression. – ProllyGeek Aug 27 '14 at 14:35
  • No problem, just try to remember that it's not how you define the function, but how you call it that matters, and if it's called with no context, it will always use the global context (window). Once you get that, it's a lot easier to grok. – adeneo Aug 27 '14 at 14:38
  • please check my own answer. – ProllyGeek Aug 27 '14 at 15:52
  • Whatever floats your goat ! – adeneo Aug 27 '14 at 16:42
2

I am afraid that the correct answer is like following (after 2 hours of searching) , this book "JavaScript Succinctly" states that:

You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (the window object in browsers), instead of the object within which the function is defined.

it also states that:

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.

so simply the answer is YES, any nested function will always return head object as reference.

Also you can use a work-around to solve this issue, by storing the value of this as soon as it is available, like following:

var myObject = {  
    myProperty: 'I can see the light', 
    myMethod : function() {
        var that = this; // Store a reference to this (i.e. myObject) in myMethod scope.
        var helperFunction = function() { // Child function.    // Logs 'I can see the light' via scope chain because that = this.
            console.log(that.myProperty); // Logs 'I can see the light'.
            console.log(this); // Logs window object, if we don't use "that".
        }(); 
    }
};  
myObject.myMethod(); // Invoke myMethod. 
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72