2

Possible Duplicate:
this operator in javascript

The term context is bit confusing me.If i declare a function within a function i.e nested function and execute there itself,like below...

function  foo(){
    function fo(){
    alert(this);
       }
    fo();
   }

the this keyword should point to the function object rather than window since function fo() is within its parent function.Since function is also an javascript object,than why the this keyword is traversing the function object and pointing to window? Also this keyword points to the current object on which the function operates ,so function object is the object on which the nested function operates.

Community
  • 1
  • 1
  • 7
    The context of `this` depends on **how** you call the function not on the function itself. – elclanrs Jan 06 '13 at 04:39
  • I am not sure what the question is. Here is a reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this – akonsu Jan 06 '13 at 04:46
  • 1
    Oh yay! Another javasrcipt `this` question. There are over 500,000 very similar questions on SO already. ...surely one of these addresses your questions: http://stackoverflow.com/search-new?q=javascript+this+ – Gerrat Jan 06 '13 at 04:48
  • I'm too lazy to answer this question, but try `new fo()` and you'll see what's happening and eventually figure out how context works in JS. – elclanrs Jan 06 '13 at 04:50
  • @elclanrs i m really getting confused ,if context is an object on which function operates than parent function is also an javascript object within which the nested function operates –  Jan 06 '13 at 04:51
  • @elclanrs how can i do new fo() since fo() is the nested function –  Jan 06 '13 at 04:57
  • Correction, `new foo()`, see @dlutxx and I's answer below. – rounce Jan 06 '13 at 05:02

4 Answers4

2

If you just call foo() in the top level, it is identical to window.foo().
And window is the actual context of foo, so, this points to the window object.

newacct
  • 119,665
  • 29
  • 163
  • 224
adamsmith
  • 5,759
  • 4
  • 27
  • 39
  • 1
    but the keyword this is within the fo() but not within foo –  Jan 06 '13 at 04:44
  • Seems you have a little misunderstanding of `context` here: The context is the object to which your current running code is attached to, not the `Function` the code is running in. @Maizere Pathak – adamsmith Jan 06 '13 at 04:47
  • i m really getting confused ,if context is an object on which function operates than parent function is also an javascript object within which the nested function operates –  Jan 06 '13 at 04:51
  • Edit made with, more info for you. – rounce Jan 06 '13 at 04:55
  • @rounce: rolled back edit. "when a function is called (ie. foo()), this is scoped to object which this points to when it's called." is incorrect – newacct Jan 06 '13 at 08:47
1

Adding to what dlutxx said. If you have a function (in the global space) and you simply call it like foo() the context is the window itself (since the function is a member of the window object). However, if you use the new keyword for getting a new instance of the function, this will refer to the function object.

function foo() {
    alert(this);
}

foo(); // "this" inside the function will be window

new foo(); // "this" inside the function will be the function object.

If you want to have a custom value for this inside the function, you can call it using .call() like:

foo.call(x); // "this" inside the function will be x

Example code for your case:

function  foo(){
    function fo(){
        alert(this);
    }
    fo(); // "this" is window
    new fo(); // "this" is the function object
    fo.call('x'); // "this" is 'x'
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • u r not concentrating in my question ,watch the code i have provided –  Jan 06 '13 at 04:59
1

If you randomly use this inside of a function which is NOT a constructor, then you will get one of a few different results:

function callThis () { return this; }


callThis(); // returns window object

var Bob = { func : callThis };

Bob.func(); // returns Bob

callThis.call(Bob);  // returns Bob

Call is a method which is used to determine the context of the call.
If the call's context can not be determined by:

a. What's in front of the "." (Bob.func();)
b. What's explicitly passed into .call(), .apply() or .bind()

Then it's set to window.

That is how context is resolved.

So if you have a specific object in mind for this, then your solutions are as follows:

function objMethod () {
    var self = this;
    function doStuff () {
        self.otherFunc();
        self.otherProperty = "bob";
    }

    doStuff();
}


var myObj = { myMethod : objMethod };
myObj.myMethod();

myObj calls objMethod with the context set to myObj.
objMethod saves a reference to the current context (myObj) as self. doStuff uses the reference to modify the properties of the referenced object.

function outer () {
    function inner () { this.property = "Bob"; }
    inner.call(this);
}


var obj = {};
outer.call(obj);

Here, outer is passed a context, using .call().
Then inner is passed the this of outer, again, using .call()

var bob = { name : "Bob" };

function sayName () { console.log(this.name); }

var bobFunc = sayName.bind(bob);
bobFunc();

Here, we use .bind() to create a version of sayName where this is always set to bob.
You can feel free to mix and match these systems all you'd like (and when dealing with async programming, you likely will).

Norguard
  • 26,167
  • 5
  • 41
  • 49
0

my understanding is that although function fo() is defined in the scope of function foo(), which means that it is not accessible from outside of foo unless you return it, the rules that apply to the value of this when you call this internal function, are still the same as if you called any other function.

function f() {
    function g() {
        console.log(this)
    }
    console.log(this);
    g();
    g.apply(this);
    }

f()           // => Window, Window, Window
f.apply(this) // => Window, Window, Window
f.apply({})   // => Object, Window, Object
akonsu
  • 28,824
  • 33
  • 119
  • 194