简体   繁体   English

在对象实例化时将变量名称拉入构造函数

[英]Pull variable name through to constructor on object instantiation

Here's an example constructor 这是一个示例构造函数

function AnObject(a, b){
    this.a = a;
    this.b = b;
}

and an instantiation of it 及其实例

var example = new AnObject('test', 'test');

Lets say that the constructor had a property .name 可以说构造函数有一个属性.name

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with? 无论如何要构建构造函数,以便将对象的名称设置为实例化的变量的名称?

In the case above, the name would be example 在上述情况下,名称将为example

- EDIT - - 编辑 -

The reason I am trying to achieve this is to be as "DRY" as possible. 我尝试实现此目的的原因是要使其尽可能“干燥”。

I would like to NOT have to: 我不想不必:

var example = new ObjectWithName('example');

is there anyway to build the constructor so that it sets the object's name to the name of the variable that it was instantiated with? 无论如何要构建构造函数,以便将对象的名称设置为实例化的变量的名称?

When you create a new object with 当您使用创建新对象时

new AnObject('test', 'test')

this results in an object reference, which can be then just used directly: 这将导致对象引用,然后可以直接使用该对象引用:

(new AnObject("test","test")).a

or discarded 或丢弃

 new AnObject('test', 'test')

or assigned to some other object property: 或分配给其他一些对象属性:

 myotherobject["b"]=new AnObject('test', 'test')

or pushed into an array: 或推入数组:

 myarr.push(new AnObject('test', 'test'))

or assigned to multiple variables at once 或一次分配给多个变量

a=b=c=d=e = new AnObject('test', 'test');

and there is no way your constructor can know in which way the object (reference) will be used, or know the name of the variable it will be assigned to (in case of simple variable assignment). 并且构造函数无法知道将使用对象(引用)的方式,也无法知道将其分配给变量的名称(在简单变量分配的情况下)。

In other words creating an object and doing something with the resulting object reference are two completely independent actions. 换句话说,创建对象并使用所得对象引用进行某些操作是两个完全独立的操作。

So unless you explicitly pass the "name" value into the constructor as the argument: 因此,除非您将“名称”值显式传递给构造函数作为参数:

var example = new AnObject('example','test','test')

or set it later on 或稍后设置

example.name="example"

there is no way you can achieve that. 您无法实现这一目标。

No. I'm afraid that's not possible! 不,恐怕不可能!

You see, the statement var example = new AnObject('test', 'test'); 您会看到语句var example = new AnObject('test', 'test'); is evaluated from right to left. 从右到左评估。 So, first new AnObject('test', 'test') is evaluated. 因此,首先new AnObject('test', 'test') Then, the value it returns is assigned to var example . 然后,将其返回的值分配给var example

Because of this right-to-left evaluation, there is no way your AnObject constructor can know that its return value is going to be assigned to variable example when it's being evaluated. 由于这种从右到左的评价,是没有办法AnObject构造函数可以知道它的返回值将被赋给变量example它被评价时。

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

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