gpt4 book ai didi

javascript - 获取对象的引用名称?

转载 作者:行者123 更新时间:2023-12-02 20:32:35 25 4
gpt4 key购买 nike

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

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。

我该怎么做?

最佳答案

对象独立于引用它们的任何变量而存在。 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.

(作为奖励,我还做了一些风格上的更改。最好将 eastwest 初始化为 null 而不是空字符串""null 更好地代表“尚未连接”的概念。并将 that 视为 object 的替代品>.)

但这提出了一个问题:为什么您要首先打印该名称。如果您的目标是能够对任何变量执行此操作(例如出于调试目的),那么您应该摆脱这个概念。如果您只是想测试连接是否正确,请考虑以下内容:

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

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

关于javascript - 获取对象的引用名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com