【问题标题】:How to add subclasses to an object in javascript如何在javascript中向对象添加子类
【发布时间】:2019-03-28 21:34:53
【问题描述】:

我想知道如何向对象添加子类,就像我在下面的代码中尝试使用的那样。

代码对于我正在尝试做的事情来说是非常不言自明的。如何将 .id、.name 和 .lastname 添加到对象?

var obj = getObjfunction(); //Get object with all info in it and show in console
console.log(obj.id);
console.log(obj.name);
console.log(obj.lastname);

function getObjfunction() {

    var obj;

    //I like to set 3 subclass to this "obj" like below. How to achieve this?
    obj.id = 0;
    obj.name = "Tom";
    obj.lastname = "Smith";
}

【问题讨论】:

  • 你说subclass是什么意思?
  • “将子类添加到对象”实际上没有意义。
  • 在这种情况下,子类可能是错误的术语。第一个答案正是我想要的。谢谢!

标签: javascript object subclass


【解决方案1】:

您似乎正在寻找的是构造函数。您可以使用new 调用它,并通过引用this 在构造函数中对其进行初始化:

var obj = new getObjfunction();
console.log(obj.id);
console.log(obj.name);
console.log(obj.lastname);

function getObjfunction() {
    this.id = 0;
    this.name = "Tom";
    this.lastname = "Smith";
}

【讨论】:

  • 谢谢,这正是我所追求的。这很好用。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 2013-09-28
  • 2014-09-09
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
相关资源
最近更新 更多