1 Answer
1

Actually this can refer to different thing, implicitly, it is set depending how you invoke a function, for exmaple:

obj.func();

The this value inside func will refer to obj.

new Func();

The this value will refer to a newly created object that inherits from Func.prototype.

func();

The this value will refer to the Global object.

And the value can be set explicitly also, using the call or apply methods, for example:

function foo () {
alert(this);
}
foo.call("hello world");

The helloWorld1 example you post, would work only if the this value refers to a function, that returns another function, because if you analyze the line:

this({ body: "Hello world!" })();

You can note that this needs to be a function, because you are invoking it, passing the object to it. And we know the return value needs also to be a function, because the last parentheses, are another function invocation.

Edit: To make the helloWorld2 example you post work, the this value needs to be a function with a pattern that allows us to chain multiple function calls, returning the same function each time, until the function is called without arguments, e.g.:

Wow, you are awesome! This helped me to understand a lot! Is there a good javascript book that you recommend that explains these kind of things? Cause the javascripts book I've read are just explaining simple things with DOM manipulations and some fancy effects.
–
never_had_a_nameSep 26 '10 at 3:03