简体   繁体   English

这些方式在javascript中定义函数是否相等?

[英]Are these way to define function in javascript equal?

I was wondering if the following way of writing function in javascript are equal. 我想知道以下javascript中的写函数是否相等。

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(xy); 如果你不相信我,试试console.log(xy); 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: 编辑:示例:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM