Reputation: 131
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.
Upvotes: 0
Views: 31
Reputation: 2190
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.
Upvotes: 0
Reputation: 370759
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
.
Upvotes: 2