JavaScript评估替代方案
我有一个调用对象:JavaScript评估替代方案,javascript,scope,this,Javascript,Scope,This,我有一个调用对象: var callingObj = { fun: myroot.core.function1, opts: { one: "abc", two: "car", three: "this.myattr1" } }; 稍后,应该调用“fun”属性的函数。此函数调用的参数应来自属性“opts”。非常重要的是,在调用函数时,变量“three
var callingObj = { fun: myroot.core.function1,
opts: { one: "abc",
two: "car",
three: "this.myattr1" } };
稍后,应该调用“fun”属性的函数。此函数调用的参数应来自属性“opts”。非常重要的是,在调用函数时,变量“three”应该具有this.myattr1的值
我知道我可以这样做:
// inside a for loop which is processing the opts attributes
if (attrValue.indexOf("this.") == 0) {
value = eval(attrValue);
paramsObj[attr] = value;
// instead of eval I could use
helpval = attrValue.substring(5);
value = this[helpval];
paramsObj[attr] = value;
}
else {
paramsObj[attr] = attrValue;
}
但是是否有一个可能的实现,我不必在“attrValue”中检查和搜索“this”并对此作出反应
提前谢谢你的帮助
更新:
attrValue在本例中是“abc”、“car”或“this.myattr1”。paramsObj是函数调用的参数对象
我把this.myattr1放在一个字符串中,因为我不知道还有什么可能说“this,但这是以后的事情”
这和myroot.core.function1不一样 类似的方法可能会奏效:
var callingObj = {
fun: myroot.core.function1,
opts: [
{value: "abc"}, // `value` for literals
{value: "car"},
{link: "myattr1"} // `link` for local vars on `this`
]
};
使用中:
// resolve args:
var opts = callingObj.opts,
args = [],
i = 0,
max = opts.length;
for (; i < max; i++) {
args.push(opts[i].link ? this[opts[i].link] : opts[i].value);
}
// apply with local scope
var result = callingObj.fun.apply(this, args);
//解析参数:
var opts=callingObj.opts,
args=[],
i=0,
最大值=选择长度;
对于(;i
这将适用于需要3个参数的函数,而不是单个
对象参数 您可以使用类似jQuery的函数来完成所需的操作。你的解释很好-它是这个
,但在以后的时间和另一个范围
var callingObj = {
fun: myroot.core.function1,
opts: { one: "abc",
two: "car",},
getVarCallback: $.proxy(this, 'getAttr1'),
};
因此,我们创建了一个代理
函数,它知道该
的作用域是什么,以便以后调用该函数,而不是像现在这样传入参数
函数getAttr1只会从定义它的对象返回myAttr1的当前值
然后,要调用该函数,只需执行以下操作:
var currentValue = callingObject.getVarCallback();
callingObj.fun(
callingObj.opts.one,
callingObj.opts.two,
currentValue
);
这是一个非常干净的方式做你所追求的。您也可以将其设置为:
var callingObj={
乐趣:myroot.core.function1,
选项:{1:“abc”,
二,"车",,
打电话者:这个,
attrFunctionName:'getAttr1'),
};
然后称之为:
var attrFunction = callingObject.attrFunctionName;
var currentValue = callingObject.caller.attrFunction();
但是jQuery代理是一种非常干净的方法,因为处理回调的函数不必知道它使用的数据是来自对象还是普通函数,这使得代码更易于维护。什么是attrValue
和paramsObj
?是'myroot.core'和'this'指向同一个对象?attrValue在本例中是“abc”、“car”或“this.myattr1”。paramsObj是函数调用的参数对象。是否尝试使用function.apply?@raghav我不确定这是否有助于计算字符串。您好,Danack!$。代理是一种非常有趣的方法!