这是创建函数对象的明智选择吗?好处?缺点
var _ = require("underscore")
function functionName(fn){
//http://stackoverflow.com/a/17923727/340688
return /^function\s+([\w\$]+)\s*\(/.exec(fn.toString())[1]
}
function objecfify(arr){
return _.chain(arr)
.map(function(fn){
return [functionName(fn), fn]
})
.object()
.value()
}
var model = objecfify([
function create(){
return "create"
},
function read(){
return "read"
},
function update(){
return "update"
},
function remove(){
return "delete"
}
])
console.log(model)
答案 0 :(得分:1)
尝试使用fn.name获取函数名称:
var functions = [
function create(){
return "create"
},
function read(){
return "read"
},
function update(){
return "update"
},
function remove(){
return "delete"
}
];
var result = functions.map(function(fn) {
return fn.name;
});
document.write(JSON.stringify(result));