[英]How can I pass a JS object literal name value pair to another function
Given a JS literal object like: 给定一个JS文字对象,如:
var foo = {
_stuff : {
a:10,
b:20,
c:30,
state
}
}
and literal functions 和文字功能
addAB: function() {
add(foo._stuff[a], foo._stuff[b]);
}
addAC: function() {
add(foo._stuff[a], foo._stuff[c]);
}
add: function(bar, baz) {
foo._stuff[bar] += foo._stuff[baz];
state(foo._stuff[bar]);
}
state: function(value) {
foo.state[value] = .... something complex ....
}
How can I get the following in one pass ? 如何一次性获得以下内容?
add(AB); foo._stuff[a] should be 30, foo.state[foo._stuff[a]] is something new
add(AC); foo._stuff[a] should be 40, foo.state[foo._stuff[a]] is something new
As is add() will try to lookup foo._stuff[10] which clearly wont do what I want. 因为add()将尝试查找foo._stuff [10],它显然不会做我想要的。
Yes I know there is redundancy with addAB() and addAC() but that is out of my control. 是的我知道addAB()和addAC()存在冗余,但这是我无法控制的。
Pass the index instead of the value, like this: 传递索引而不是值,如下所示:
addAB: function() {
add('a', 'b');
}
addAC: function() {
add('a', 'c');
}
add: function(bar, baz) {
if (arguments.length === 1) {
this['add' + arguments[0]];
} else {
foo._stuff[bar] += foo._stuff[baz];
state(foo._stuff[bar]);
}
}
// assuming you are calling
var AB = 'AB', AC = 'AC';
add(AB);
add(AC);
Otherwise, I have not a clue what you are asking. 否则,我不知道你在问什么。
I'm not sure if I totally follow what you want to accomplish, but your object literal is not valid syntax. 我不确定我是否完全遵循你想要完成的任务,但你的对象文字不是有效的语法。 I don't see why you want the _stuff
property. 我不明白为什么你想要_stuff
属性。 And, you need to initialize the state
property to some value, even if it's undefined. 并且,您需要将state
属性初始化为某个值,即使它未定义。 But, since you want to store values in the state
property based on some property name, you should initialize state
to be an object. 但是,由于您希望根据某个属性名称在state
属性中存储值,因此应将state
初始化为对象。
var foo = {
a:10,
b:20,
c:30,
state: {}
}
Your javascript: 你的javascript:
addAB: function() {
add('a', 'b');
}
addAC: function() {
add('a', 'c');
}
add: function(propName0, propName1) {
foo[propName0] += foo[propName1];
state(propName0);
}
state: function(propName) {
// state is initialized to an object, so can store properties in there now
foo.state[propName] = .... something complex ....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.