I have code like this:
function demo() {
this.val=5;
function() {
this.val=7;
}();
}
Now when I give execute this code in the firefox or chrome console it gives a syntax error. I don't understand why this is an error because I have read that javascript functions are objects so when I call the anonymous function, inside it this
points to function demo and should change the val
to 7
, so if I do
var x=new demo();
x.val; //should give 7
but when I do this
function demo() {
this.val=5;
var f=function() {
this.val=7;
}();
}
window.val; // gives 7
I don't understand if functions are objects then why the this
in the anonymous function points to window
and not demo
.
Please explain this.
i dont understand why this is an error
because
function() {
this.val=7;
}();
is evaluated as function declaration and function declarations need a name. To make it interpreted as function expression, you need to put it in parenthesis:
(function() {
this.val=7;
}());
(making it an immediate function)
or assign the function to a variable:
var f = function() {....};
f();
What you do in the second snippet is a mixture of both and although being valid, it does not make much sense. f
will have the value undefined
.
i dont understand if functions are objects then why the this in the anonymous function points to
window
and notdemo
.
Functions don't inherit the context they are called in. Every function has it's own this
and what this
refers to is determined by how the function is called. It basically boils down to:
"Standalone" ( func()
) or as immediate function ( (function(){...}())
) : this
will refer to the global object (window
in browsers)
As property of an object ( obj.func()
): this
will refer to obj
With the new
[docs] keyword ( new Func()
): this
refers to an empty object that inherits from Func.prototype
apply
[docs] and call
[docs] methods ( func.apply(someObj)
): this
refers to someObj
Further reading:
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