Javascript'new',函数返回自定义对象

问题描述:

假设我有以下功能:

var A = function() {
   var label = "hello";
   return {
      getLabel: function() { return label; }
   }
};

之间有什么区别:

var a = A();

var a = new A();

注意:我是不要在这里问 JavaScript中的'新'关键字,但它是如何在这个特定的例子中表现的。

NB: I'm not asking here what is the 'new' keyword in JavaScript, but how it behaves in this particular example.

在你的特定实例中,,没有差异。

In your particular instance, No, there is no difference.

无论如何,你的函数将返回一个自定义对象。通过使用 new 关键字调用函数,ECMAscript将自动为您创建一个新对象(同时使用原型做一些魔术>和构造函数属性),你可能访问 / 通过 函数中的code>(-constructor)。

Eitherw way, your function will return a self defined Object. By invoking a function with the new keyword, ECMAscript will automatically create a new object for you (alongside doing some magic with prototype and constructor properties), which you might access / write to via this within the function (-constructor).

再次,你的 return {} 在该函数中调用,将始终返回该对象引用。

Again, your return { } call in that function, will always return exactly that object reference.