Can anyone explain this simple Javascript behavior?

function cat() {

    this.Execute = new function() {

            alert('meow');

    }

}

var kitty = new cat();

http://jsfiddle.net/PaDxk/1/

Why is this so? I did not say that it performed the function.

+3
source share
3 answers

When you write new function() { ... }, you create an anonymous function, and then immediately call it in the expression new.
The result of this expression is an object - an instance of a class created by an anonymous function.

It is equivalent

var anonymous = function() { ... };
this.Execute = new anonymous;
+8
source

An anonymous warning function in it is used as a constructor (because of new). this.Executethen becomes an “instance” of this functional object.

+4
source

- "".

, :

function cat() {

    this.Execute =  function() {  
            alert('meow');    
    }    
}

var kitty = new cat();
kitty.Execute(); 

, , .

+3

All Articles