开发者

Are these way to define function in javascript equal?

开发者 https://www.devze.com 2023-04-05 13:11 出处:网络
I was 开发者_开发知识库wondering if the following way of writing function in javascript are equal.

I was 开发者_开发知识库wondering if the following way of writing function in javascript are equal.

To me it seems they produce the same result, but in what they can be different?

First way:

(function(){
    alert('ciao')
})();

Second way:

new function bar(){alert('ciao')}; 


The second one returns a new instance of the function, as if it was a constructor.

So, these are equivelent:

Traditional method:

function bar() {
    this.x = 5;
};
var x = new bar();

Lazy one-liner.

var x = new function bar() { this.x = 5; };

The only difference is that you cannot reuse bar later.

If you don't believe me, try console.log(x.y); on both examples.

Your first example is an anonymous function which is not instantiated, it is just called.


The first one executes the function and returns the result of it. The second one executes the function and returns an object.

EDIT: example:

Are these way to define function in javascript equal?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号