Reputation: 1
I am collaborating on a dynamically generated web page that uses mustache and js to determine what to display. I want to have a function that returns one object given a certain global condition and a different object if that condition is not the case, but I can't seem to get it to work.
getNameTokens: function() {
var tokens;
if(world.indexOf('9') == 1 ||world.indexOf('9') == 0) {
tokens = {agent: 'president', ent: 'company', ownsf: 'the company\'s', owns: 'its'};
} else {
tokens = {agent: 'player', ent: 'player', ownsf: 'his', owns: 'his'};
}
return tokens;
},
'tokenNames': getNameTokens(),
Am I doing somthing wrong here?
Upvotes: 0
Views: 54
Reputation: 29906
It looks like your code is part of an object literal, like:
var world = '9876';
var Service = {
getNameTokens: function() {
var tokens;
if(world.indexOf('9') == 1 ||world.indexOf('9') == 0) {
tokens = {agent: 'president', ent: 'company', ownsf: 'the company\'s', owns: 'its'};
} else {
tokens = {agent: 'player', ent: 'player', ownsf: 'his', owns: 'his'};
}
return tokens;
},
'tokenNames': getNameTokens()
};
In this case, you can't just write 'tokenNames': getNameTokens(),
, as there is no getNameTokens()
function in the
scope. There will be a Service.getNameTokens()
function, but only after the object gets constructed. To use it during
the construction define it separately:
var world = '9876';
function getNameTokens() {
var tokens;
if(world.indexOf('9') == 1 ||world.indexOf('9') == 0) {
tokens = {agent: 'president', ent: 'company', ownsf: 'the company\'s', owns: 'its'};
} else {
tokens = {agent: 'player', ent: 'player', ownsf: 'his', owns: 'his'};
}
return tokens;
}
var Service = {
getNameTokens: getNameTokens,
'tokenNames': getNameTokens()
};
Upvotes: 0
Reputation:
Probability it should be something like this:
var world = [0,2,3,5,5,];
var getNameTokens = function(element) {
var tokens = {};
if(world.indexOf(element) <= 1) {
tokens = {
agent: 'president',
ent: 'company',
ownsf: 'the company\'s',
owns: 'its'
};
} else {
tokens = {
agent: 'player',
ent: 'player',
ownsf: 'his',
owns: 'his'
};
}
return tokens;
}
var newObj = getNameTokens(0);
console.log(newObj)
Fiddle example. Or It could be also as @Krystian Laskowski has described
Upvotes: 1
Reputation: 333
Unfortunately, you cannot invoke object method in this object literal. That is because an object literal is only a list of key/value pairs. It doesn't contain any instantiation logic (i.e. constructor).
I guess that the solution for your problem might be something like this:
function objectFactory(){
var getNameTokens = function() {
var tokens;
if(world.indexOf('9') == 1 ||world.indexOf('9') == 0) {
tokens = {agent: 'president', ent: 'company', ownsf: 'the company\'s', owns: 'its'};
} else {
tokens = {agent: 'player', ent: 'player', ownsf: 'his', owns: 'his'};
}
return tokens;
}
var result = {
getNameTokens: getNameTokens,
tokenNames: getNameTokens
}
return result;
}
Upvotes: 0