dynobj = {};
methods = ["method1","method2", "method3"];
for (var i = 0; i < methods.length; i++) {
dynobj[methods[i]] = function () {
alert("I am " + i);
};
};
dynobj.method2();
dynobj.method1();
我希望&#34;我是1&#34;和&#34;我是0&#34;但是&#34;我是3&#34;和&#34;我是3&#34;。我期待的行为正确的方法是什么?
答案 0 :(得分:4)
尝试以下方法:
var dynobj = {};
var methods = ["method1", "method2", "method3"];
var length = methods.length;
for (var i = 0; i < length; i++) {
dynobj[methods[i]] = (function (i) {
return function () {
alert("I am " + i);
};
}(i));
}
dynobj.method2();
dynobj.method1();