I'm fairly new to JavaScript I setup below to use keys and values for different items I need to work. All the values will be the same using a variable to distinguish each item (which will just be it, but I would like to identify each item (itemObject) which I'm also using for the variable name.
Abbreviated example::
function objFunction (itemName) {
itemObject = {
object1Data: [{
data1: {
prop1: 'value',
prop2: 'value'
},
data2: {
prop1: itemName + 'some string'
prop2: itemNamevariable
}
}],
object2: {
data: {
prop1: itemName,
prop2: itemName + 'some string'
}
}
}
}
Or am I better off using a constructor or another method?
function ObjFunction (itemName) {
this.itemObject = {
bject1Data: [{
data1: {
prop1: 'value',
prop2: 'value'
},
data2: {
prop1: itemName + 'some string',
prop2: itemName
}
}],
object2: {
data: {
prop1: itemName,
prop2: itemName + 'some string'
}
}
}
}
var item1 = new ObjFunction('item1Name');
I prefer the first answer, just change the second line from:
itemObject = {
to
return {
and then you can say:
var item1 = objFunction('item1Name');
In other words:
function objFunction (itemName) {
return {'name' : itemName};
}
var y = objFunction("theName");
console.log(y.name);
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.