使用返回对象的Object构造函数.这个怎么运作? [英] Using Object constructors that return objects. How it works?

查看:51
本文介绍了使用返回对象的Object构造函数.这个怎么运作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在创建JS对象,例如 a = {} 或此 a = new MyConstructor()而不考虑太多.

I've been always creating JS objects like this a = {} or this a = new MyConstructor() without thinking much about it.

然后我想出了一些看起来像这样的代码:

Then I came up with some code that looks like this:

function Constructor(){
    var private = {
          a:1,
          b:2
    };
    return private;
}


var a = new Constructor();

现在,

a 自然包含了 private 对象的新实例.然后我意识到不需要 new 运算符,因为每次调用 Constructor 函数时都会创建 private 对象.

a naturaly now contains a new instance of the private object. And then I realised that the new operator is not required because the private object gets created every time the Constructor function gets called.

因此,实际问题是:调用 new Constructor()时会发生什么?

So the actual question is: What happens when calling new Constructor()?

为什么不应该只使用 a = Constructor()?

Constructor 对象的任何公共属性会发生什么?

What happens to any public properties of the Constructor object if any?

从构造函数返回对象不是一个好主意吗?

Is returning objects from a constructor a bad idea?

推荐答案

调用 new Constructor()会发生什么?

请查看 new 运算符 JavaScript中的"new"关键字是什么?问题.

创建一个实例(例如 Object.create(Constructor.prototype)),可以通过 Constructor 函数中的 this 对其进行访问.但是,调用的结果将只是分配给 a 的返回对象( private ).

An instance is created (like Object.create(Constructor.prototype)), which is accessible via this inside the Constructor function. However, the result of the call will only be the returned object (private), that is assigned to a.

为什么不应该只使用 a = Constructor()?

实际上,您应该这样做. Constructor 不是构造函数,它不创建实例-它仅返回 private 对象.因此,请勿使用 new .但是,您还应该重命名该函数,以便使其清晰可见,例如到 makeXYZ().

Actually, you should do this. Constructor is not a constructor, it doesn't create instances - it just returns the private object. Therefore, don't use new. However, you should also rename the function so that it is clear, e.g. to makeXYZ().

如果 Constructor 对象的任何公共属性发生了什么情况,有吗?

What happens to any public properties of the Constructor object if any?

a b 是返回对象的公共"属性.
如果您在 Constructor 函数本身上表示静态"属性,则它们什么都没有发生.
如果您是说 Constructor.prototype 上的共享"属性-它们什么也没有发生,则它们不会被返回的对象继承(这可能不是本意).

a and b are the "public" properties of the returned objects.
If you mean "static" properties on the Constructor function itself, nothing happens to them.
If you mean "shared" properties on the Constructor.prototype - nothing happens to them, they do not get inherited by the returned objects (which is probably not what was intended).

从构造函数返回对象不是一个好主意吗?

Is returning objects from a constructor a bad idea?

从构造函数开始,是的.
从一般的功能来看,没有.将其设为普通的工厂函数(即返回对象的函数),这是一种很好的模式

From constructors, yes.
From functions in general, no. Make it a normal factory function (i.e. a function that returns objects), which is a fine pattern.

这篇关于使用返回对象的Object构造函数.这个怎么运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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