我想知道如何将子类添加到对象中,就像我尝试在下面的代码中使用一样。
对于我想要做的事情,代码是非常自我解释的。如何将.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";
}
你似乎在寻找的是一个构造函数。您可以使用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";
}