Reputation: 52952
function cat() {
this.Execute = new function() {
alert('meow');
}
}
var kitty = new cat();
Why does it do that? I haven't told it to run the function.
Upvotes: 2
Views: 98
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
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
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