我正在使用动态生成的网页进行协作,该网页使用小胡子和js来确定要显示的内容。我希望有一个函数在给定某个全局条件的情况下返回一个对象,如果不是这种情况则返回另一个对象,但我似乎无法让它工作。
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(),
我在这里做错了吗?
答案 0 :(得分:1)
概率它应该是这样的:
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示例。或者也可以像@Krystian Laskowski所描述的那样
答案 1 :(得分:0)
不幸的是,您无法在此对象文字中调用对象方法。这是因为对象文字只是键/值对的列表。它不包含任何实例化逻辑(即构造函数)。
我想你的问题的解决方案可能是这样的:
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;
}
答案 2 :(得分:0)
看起来您的代码是对象文字的一部分,例如:
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()
};
在这种情况下,您不能只写'tokenNames': getNameTokens(),
,因为此处没有getNameTokens()
功能
范围。 将成为Service.getNameTokens()
函数,但仅在构造对象之后。在期间使用它
结构分别定义:
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()
};