如何在javascript中向对象添加子类

问题描述 投票:-3回答:1

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

对于我想要做的事情,代码是非常自我解释的。如何将.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";
}
javascript object subclass
1个回答
3
投票

你似乎在寻找的是一个构造函数。您可以使用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";
}
© www.soinside.com 2019 - 2024. All rights reserved.