var obj = {};
var funNames = ['get', 'set'];
for(var item in funNames){
var funName = funNames[item];
obj[funName] = function(){
console.log(funName);
}
}
obj.get();
obj.set();
最后两个都输出 set, 我想实现的是一个输出 get, 一个输出set
6 回复
用闭包可以实现
var obj = {};
var funNames = ['get', 'set'];
for(var item in funNames){
var funName = funNames[item];
function some(funName){
return function() {
console.log(funName);
}
}
obj[funName] = some(funName);
}
obj.get();
obj.set();
var obj = {};
var funNames = ['get', 'set'];
for(var item in funNames){
var funName = funNames[item];
//动态生成function
obj[funName] = new Function("console.log('" + funName + "');");
}
obj.get();
obj.set();