1

For the following piece of code

a.b = function c(){
    return function e(){
        return this;
    };
};
d = a.b();

What will the value of d() be? This might not be a very good example, but I am just confused about what "this" will refer to.

Thanks,

stupidguy
  • 411
  • 1
  • 5
  • 10

6 Answers6

4

Seeing as d will now equal a FUNCTION, "this" will be evaluated to whatever function calls it. It hasn't actually been evaluated yet.

At the end of execution, d='function e() { return this; }', so the moment you execute d() is when this will be evaluated.

DanRedux
  • 9,119
  • 6
  • 23
  • 41
  • 2
    But in this case `this` will be evaluated to `window` when `d()` is called. – bfavaretto May 02 '12 at 04:22
  • Exactly, WHEN `d()` is finally evaluated, but you're right. The reason this is the case as everything that isn't a child of an object is a child of the window, so think of `d()` as `window.d()`, hence why this refers to the window. – DanRedux May 02 '12 at 04:27
1

From your code d is not the same as the "this". d will be a the function e, since you are setting d to be return value of the function call a.b() which returns a function, so

d = function e(){
    return this;
}

Now the value of this depends upon how you call this function d. this will be evaluated when this function is called. If you just call it like d() this will be the global Window Object.

and lets say if I have

obj ={foo:1, bar:2};

and I call like this

d.call( obj )

this will be the object obj. the call() method is used to call a function on any object, the passed object behaves as this inside that function.

I know Javascript this is really confusing and it isn't easy to get your head around it. May be this can help http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx

Abid
  • 7,149
  • 9
  • 44
  • 51
0

this is an implicit parameter to all functions.

See apply and call

If you know python, this is just like self, but not explicitly written and always there

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
0

this is normally the caller of a function

$('.image').each(function(index){
    alert($(this).attr('href'));
}

I think a.b() will return a

see http://remysharp.com/2007/04/12/jquerys-this-demystified/

Charlie Wu
  • 7,657
  • 5
  • 33
  • 40
0

Assuming d() was called immediately after the last line of your snippet d() will return the global object: window if you're in a browser.

However both of these are true:

d.call(a) === a;
d.call(a.b.prototype) === a.b.prototype;

which is to say that this is defined by what is passed in as the first argument to call.

quodlibetor
  • 8,185
  • 4
  • 35
  • 48
0

this is a reference to the object on which method was called. d() is similar window.d() (if there is no with instruction)