假设查看方法长度:
fun=function(a,b,c) {
console.log(a,b,c)
}
(a,b,c) {
console.log(a,b,c)
}
fun.prototype.constructor.length
3
正如@madara-uchiha 所说,可能被认为是一种不好的做法,该bluebird
库有一个方法调用函数,即:
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
[更新]
我添加了 Bluebird 代码的工作片段来讨论它。正如有人所说,这似乎适用于其他东西,即使在 switch 案例中有一个方法长度保护。检查代码:
var console={}
console.log=function(msgs) { document.writeln(msgs)};
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
var len = this.length; \n\
console.log(\"Who is this\"+this); \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + JSON.stringify(obj) + " has no method '" +
JSON.stringify(methodName) + "'";
throw new Error(message);
}
return fn;
}
var fn=makeMethodCaller("callMe");
console.log(fn)
var obj0= {
callMe : function() { console.log("\n\n\ncalled with 0 params")}
};
var obj1= {
callMe : function(a) { console.log("\n\n\ncalled with 1 params")}
};
var obj2= {
callMe : function(a,b) { console.log("\n\n\ncalled 2 params")}
};
var obj3= {
callMe : function(a,b,c) { console.log("\n\n\ncalled 3 params")}
};
[obj0,obj1,obj2,obj3].map(function(e) {
return fn( e );
});