我想用以下函数setDef()设置一个变量。
我的例子不起作用。我该怎么办?
var defs = {
title: document.title,
action: "pageview"
};
var setDefs = function(a,b) {
defs.a= b; // this: defs.title = b; is working.
};
setDefs("title","test");
答案 0 :(得分:3)
使用括号表示法object[variable]
代替:
var setDefs = function(a,b) {
defs[a] = b;
};
此外,最好将此方法包含在对象中:
var defs = {
title: document.title,
action: "pageview",
setDefs: function(a,b) {
this[a] = b;
}
};
defs.setDefs("title","test");
// > defs
// Object {title: "test", action: "pageview", setDefs: function}