Mostafa Maher
Mostafa Maher

Reputation: 44

Getting the object variable name for the new object

I have an object constructor such as:

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

I want this results:

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

Upvotes: 1

Views: 598

Answers (3)

Abhishek Raj
Abhishek Raj

Reputation: 490

you can make a function constructor myObjConstr(), thenafter you can make new myObjConstr().

1) function constructor

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

2) make object of type myObjConstr

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

3) if you want to print the value,

console.log(name1.objName)

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36574

You can't pass the variable name to the constructor. Instead you can convert an array of names of variables to array of objects

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

Upvotes: 0

AlanK
AlanK

Reputation: 9833

You would need to pass the object name to the constructor:

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

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

Upvotes: 3

Related Questions