javascript - 有没有办法确定参数是否是 JavaScript 中的方法?
问题描述
有没有办法检查传递给函数的参数是否是方法?
例如,我想在函数内部确定输入之一是方法还是独立函数:
function isMethod(collection, fct) {
var isFct = (typeof fct === 'function');
var isProperty = (collection.hasOwnProperty(fct)); // doesn't work b/c fct = object1.methodFct, not methodFct
return `${isFct}, ${isProperty}`;
}
function nonMethodFct(a, b) {
return a + b;
}
var object1 = {
methodFct(a, b) {
return a + b;
}
};
console.log(typeof object1.methodFct === 'function' && object1.hasOwnProperty('methodFct')); // returns true
var expectTrueFalse = isMethod(object1, nonMethodFct); // returns true, false
console.log(expectTrueFalse);
var expectTrueTrue = isMethod(object1, object1.methodFct); // returns true, (false)
console.log(expectTrueTrue);
由于 undefined 的输入'methodFct'
返回错误(因为methodFct
隐藏在 的词法范围内object1
),所以我必须在属性访问器符号 ( object1.methodFct
) 中输入它,这会破坏isProperty
函数内部的检查。
换句话说,我想做独立的事情console.log()
,但我不知道如何用参数而不是硬编码的字符串来做。
我玩过JSON.stringify
and.toString()
但他们似乎只是将 and 的全部内容串起来,collection
而fct
不是他们的名字。
解决方案
利用fct.name
function isMethod(collection, fct) {
console.log(`fct.name = '${fct.name}'`);
return (typeof collection[fct.name] === 'function');
}
function nonMethodFct(a, b) {
return a + b;
}
var object1 = {
methodFct(a, b) {
return a + b;
}
};
var expectFalse = isMethod(object1, nonMethodFct); // false
console.log(expectFalse);
var expectTrue = isMethod(object1, object1.methodFct); // true
console.log(expectTrue);
推荐阅读
- javascript - 如何在没有 console.log() 的情况下记录 JavaScript 变量的值?
- javascript - 如何在初始页面加载之前加载 CSS 数据主题以防止主题之间闪烁?
- python - django项目中实时聊天的问题
- python - 尝试解决地图和 lambdas 的问题
- java - 如何优化此解决方案以避免超出时间限制?
- excel - Excel 日期根据另一个日期在下个月递增
- sql - 连接条件,中间 SQL
- python - 设置 ttk.Combobox 的样式
- regex - pandas dataframe 根据另一列的聚合过滤带有关键字的列
- python - 创建动态链接变量