NibblyPig
NibblyPig

Reputation: 52952

Can anyone explain this simple Javascript behaviour?

function cat() {

    this.Execute = new function() {

            alert('meow');

    }

}

var kitty = new cat();

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

Why does it do that? I haven't told it to run the function.

Upvotes: 2

Views: 98

Answers (3)

sharpner
sharpner

Reputation: 3957

Because of the use of "new".

if you only want to assign the function and call it later, then you need to use it like this:

function cat() {

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

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

when you use new in this context, your function behaves as if it is the constructor..

Upvotes: 3

SLaks
SLaks

Reputation: 888107

When you write new function() { ... }, you're creating an anonymous function, then calling it immediately in a new expression.
The result of this expression is an object—an instance of the class created by the anonymous function.

It's equivalent to

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

Upvotes: 8

Kuroki Kaze
Kuroki Kaze

Reputation: 8481

Anonymous function with alert in it is used as constructor (because of new). this.Execute then becomes "instance" of this function object.

Upvotes: 4

Related Questions