简体   繁体   中英

use variable to access the constructor and obtain intended string

function Title(mainTitle){
  this.mainTitle = mainTitle;
}

var projectTitle1 = new Title("Project-1 Main Title"),
projectTitle2 = new Title("Project-2 Main Title"),
projectTitle3 = new Title("Project-3 Main Title"),
projectTitle4 = new Title("Project-4 Main Title");

I like to access the constructor and pull a title relevant to a given index(1-4). I tried the following:

  var index = 4,
  x = "projectTitle" + index,
  y = projectTitle.mainTitle;

console.log(y) return undefined.

You can't "access the constructor" after it's run. What you could do, however, is to put each instantiation into an array, and access the appropriate index:

 function Title(mainTitle){ this.mainTitle = mainTitle; } const titles = [ new Title("Project-1 Main Title"), new Title("Project-2 Main Title"), new Title("Project-3 Main Title"), new Title("Project-4 Main Title"), ]; const getTitle = titleNum => titles[titleNum - 1].mainTitle; console.log(getTitle(4)); console.log(getTitle(2)); 

Of course, you'd have to be adding items to titles in order. If that can't be relied on, another possibility would be to put each title into an object indexed by the number in its mainTitle .

Simply use an array or object.

var titles=[
    //add elements here
    new Title("Project-1 Main Title"),
    new Title("Project-2 Main Title")
];
//add a new element after
titles.push(new Title("Project-3 Main Title"));

Then access each element by it's index, starting from 0 , titles[index] .

Or you could use an object to have a key (property name) for each element.

var titles={
    //define elements (properties) here
    "projectTitle1":new Title("Project-1 Main Title")
    "projectTitle2":new Title("Project-2 Main Title")
};
//assign a new element
titles.projectTitle3=new Title("Project-3 Main Title");

Then you can access each element as titles.projectTitle1 or from a string as titles[x] .

But you should know why your code doesn't work.

var index = 4,
   x = "projectTitle" + index

You have x with projectTitle4 as value.

y = projectTitle.mainTitle;

projectTitle is not defined and you never even used x .

Having the variable name as string, if that's running in the global scope (outside a function), you can access the variable projectTitle4 as window[x] .

You could easily make your current code work now. But use the array/object way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM