获取新对象的对象变量名称

时间:2019-02-14 13:12:09

标签: javascript variables logging constructor variable-assignment

我有一个对象构造函数,例如:

function myObjConstr () {
    console.log(object_name);
}

我想要这个结果:

var name1 = new myObjConstr(); //print in console log "name1"
var nameff = new myObjConstr(); //print in console log "nameff"

3 个答案:

答案 0 :(得分:3)

您需要将对象名称传递给构造函数:

function myObjConstr (obj_name) {
    this.object_name = obj_name;
    console.log(this.object_name);
}

var name1 = new myObjConstr("name1");
var nameff = new myObjConstr("nameff"); 

答案 1 :(得分:1)

您可以创建一个函数构造函数myObjConstr(),然后再创建新的myObjConstr()。

1)函数构造函数

function myObjConstr (objName) {
    this.objName = objName;
}

2)将对象设置为myObjConstr

var name1 = new myObjConstr("name1");
var name2 = new myObjConstr("name2");

3)如果要打印该值,

console.log(name1.objName)

答案 2 :(得分:0)

您不能将变量名传递给构造函数。相反,您可以将变量名称的array转换为objects的数组

let names = [
  'name1',
  'nameff'
]
let objects = names.map(name => myObjConstr(name));
function myObjConstr(name){
  this.name = name;
  console.log(this.name);
}