I have a code like this:
function demo() {
this.val=5;
function() {
this.val=7;
}();
}
Now, when I give the execution of this code in the firefox or chrome console, it gives a syntax error. I don’t understand why this is a mistake, because I read that javascript functions are objects, so when I call an anonymous function, inside it thispoints to a demonstration of the function and should change valto 7, so if I do
var x=new demo();
x.val;
but when i do it
function demo() {
this.val=5;
var f=function() {
this.val=7;
}();
}
window.val;
I don’t understand if functions are objects, why thisin an anonymous function points to window, and not demo. Please explain this.
source
share