我在另一个对象中有一个对象:
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。
我该怎么做?
答案 0 :(得分:1)
对象的存在独立于引用它们的任何变量。 new TextInput()
对象对保存对它的引用的textInput1
变量一无所知;它不知道自己的名字。如果你想知道它,你必须告诉它它的名字。
明确存储名称。将名称传递给构造函数并将其存储在.name
属性中,以便以后可以访问:
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
而不是空字符串""
。{{1更好地表示“尚未连接”的概念。并将null
视为that
的替代。)
这引发了一个问题,即为什么要首先打印名称。如果您的目标是能够通常使用任何变量(例如,出于调试目的),那么您应该摆脱这个概念。如果您只是想测试连接是否正确,请考虑以下事项:
object
这测试连接已建立并使用三元alert(textInput1.east === textInput2 ? "it worked" : "uh oh");
运算符打印两条消息之一。
答案 1 :(得分:1)
puts(textInput1.east.name)
这给出了一个undefined,因为JS试图在east中找到一个名为name的对象,该对象不存在。如果你想传递这个名字,那么我认为你需要传递一个字符串。您可以考虑在east中创建一个属性名称,该名称可以用字符串命名。但是如果有很多物品并且你正在寻找每个物体的名称那么你就不能继续这样做了。不好的做法。