Javascript'new',函数返回自定义对象 [英] Javascript 'new' with function returning self-defined object

查看:98
本文介绍了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.

这篇关于Javascript'new',函数返回自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆