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.
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;
Anonymous function with alert in it is used as constructor (because of new
). this.Execute
then becomes "instance" of this function object.
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..
精彩评论