【问题标题】:How to see the name of an instance of the class in the class如何在类中查看类的实例名称
【发布时间】:2023-02-05 02:23:28
【问题描述】:

如果这个问题措辞不当,我提前道歉。我怎么能这样做:

class MyClass {
  seeName() {
    // ...
  }
}

const foo = new MyClass();
console.log(foo.seeName()); // prints "foo"

const bar = new MyClass();
console.log(bar.seeName()); // prints "bar"

【问题讨论】:

  • 这是不可能的。没有从对象到变量的链接。
  • 如果你做bar = foo; bar.seeName(),你期望发生什么?
  • 为什么你认为你需要这样做?如果实例应该有名称,请将其设为属性。

标签: javascript class instance


【解决方案1】:

你可以这样做:

class MyClass {
  constructor(name){
    this.name = name;
  }

  seeName() {
    return this.name;
  }
}

const foo = new MyClass("foo");
console.log(foo.seeName()); // prints "foo"

const bar = new MyClass("bar");
console.log(bar.seeName()); // prints "bar"

然后你在创建对象时传入的名称将存储在对象中,但它实际上并不知道它存储在其中的变量的名称。

如果你想要一个更好的答案,请指定你想用这个名字做什么,以及你一般想做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2013-04-09
    • 2011-10-08
    相关资源
    最近更新 更多