What is the context of an anonymous function?

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;   //should give 7

but when i do it

function demo() {
    this.val=5;
    var f=function() {
            this.val=7;
    }();
}
window.val;    // gives 7

I don’t understand if functions are objects, why thisin an anonymous function points to window, and not demo. Please explain this.

+5
source share
2 answers

,

function() {
    this.val=7;
}();

, . , :

 (function() {
    this.val=7;
 }());

( )

:

var f = function() {....};
f();

, , , , , . f undefined.

, , window, demo.

, . this , this, , . :

  • "" (func()) ((function(){...}())): this (window )

  • (obj.func()): this obj

  • new [docs] (new Func()): this Func.prototype

  • apply [docs] call [docs] (func.apply(someObj)): this someObj


:

+15

, :

function demo() {
    var self=this;

    this.val = 5;

    var f = (function() {
        self.val = 7;
    })();
}
0

All Articles