Javascript - 动态创建方法?

时间:2014-02-15 11:34:37

标签: javascript

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;。我期待的行为正确的方法是什么?

1 个答案:

答案 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();

请参阅演示:http://jsfiddle.net/3Fxv5/