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!" })
();
}
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.
For example:
var fn = function(o){
return function () {
alert(o.body);
}
};
helloWorld1.call(fn); // or the equivalent
fn.method = helloWorld1;
fn.method();
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.:
var fn = (function(){
var msg = '';
return function inner (o) {
if (o) { // called with an argument?
msg += o.body;
} else { // no, show the message
alert(msg);
}
return inner; // return a reference to itself
};
})();
function helloWorld2() {
this
({ body: "Hello, " })
({ body: "my " })
({ body: "world!" })
();
}
helloWorld2.call(fn); // "Hello my world!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With