如何向 javascript 中的对象添加子类
How to add subclasses to an object in javascript
我想知道如何将子类添加到一个对象,就像我在下面的代码中尝试使用的那样。
对于我要尝试做的事情,该代码是不言自明的。如何将 .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";
}
我想知道如何将子类添加到一个对象,就像我在下面的代码中尝试使用的那样。
对于我要尝试做的事情,该代码是不言自明的。如何将 .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";
}