I understand that “this” is a reference for the caller object.
I’m used to see “this” in code like:
var Person = function() {
this.name = "foo";
}
But then I saw these lines of code:
Example 1:
function helloWorld1() {
this({ body: "Hello world!" })();
}
Example 2:
I also seen this code:
function helloWorld2() {
this
({ body: "Hello, " })
({ body: "world!" })
();
}
- What does “this” means here?
- What is happening in the above examples?
Actually
thiscan refer to different thing, implicitly, it is set depending how you invoke a function, for exmaple:The
thisvalue insidefuncwill refer toobj.The
thisvalue will refer to a newly created object that inherits fromFunc.prototype.The
thisvalue will refer to the Global object.And the value can be set explicitly also, using the
callorapplymethods, for example:The
helloWorld1example you post, would work only if thethisvalue refers to a function, that returns another function, because if you analyze the line:You can note that
thisneeds 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.For example:
Edit: To make the
helloWorld2example you post work, thethisvalue 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.: