获取对象的引用名称? [英] Get the reference name of an object?

查看:94
本文介绍了获取对象的引用名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个对象中有一个对象:

I have an object inside another object:

function TextInput() {
    this.east = "";
    this.west = "";
}

TextInput.prototype.eastConnect = function(object) {
    this.east = object;
    object.west = this;
}

textInput1 = new TextInput();
textInput2 = new TextInput();

textInput1.eastConnect(textInput2);

puts(textInput1.east.name) // this gives undefined.

在最后一个语句中,我想打印出对象的引用名称,在本例中为:textInput2。

In the last statement I want to print out the object's reference name, in this case: textInput2.

我该怎么做?

推荐答案

对象独立存在引用它们的变量。 new TextInput()对象对<000 c> c> textInput1 变量一无所知,该变量包含对它的引用;它不知道自己的名字。如果你想知道它,你必须告诉它它的名字。

Objects exist independently of any variables that reference them. The new TextInput() object knows nothing about the textInput1 variable that holds a reference to it; it doesn't know its own name. You have to tell it its name if you want it to know.

明确存储名称。将名称传递给构造函数并将其存储在 .name 属性中,以便以后可以访问:

Store the name explicitly. Pass the name to the constructor and store it off in the .name property so it's accessible later:

function TextInput(name) {                  // Added constructor parameter.
    this.name = name;                       // Save name for later use.
    this.east = null;
    this.west = null;
}

TextInput.prototype.eastConnect = function(that) {
    this.east = that;
    that.west = this;
}

textInput1 = new TextInput("textInput1");   // Pass names to constructor.
textInput2 = new TextInput("textInput2");

textInput1.eastConnect(textInput2);

puts(textInput1.east.name);                 // Now name is available.

(作为奖励我也做了一些风格上的修改。最好初始化 east west null 而不是空字符串 null 更好地表示尚未连接的概念。并考虑 作为对象的替代。)

(As a bonus I also made a few stylistic changes. It's better to initialize east and west to null rather than an empty string "". null better represents the concept of "no connection yet". And consider that as an alternate for object.)

这引发了为什么要在名称中打印名称的问题不过,第一名。如果您的目标是能够通常使用任何变量(例如,出于调试目的),那么您应该摆脱这个概念。如果您只是想测试连接是否正确,请考虑以下事项:

This raises the question of why you want to print the name in the first place, though. If your goal is to be able to do this in general with any variable (for debugging purposes, say), then you ought to get rid of that notion. If you're just trying to test that the connection was made properly, consider something like this:

alert(textInput1.east === textInput2 ? "it worked" : "uh oh");

这测试连接是否已使用三元? :运算符可以打印两条消息之一。

This tests that the connection was made and uses the ternary ? : operator to print one of two messages.

这篇关于获取对象的引用名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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