首页 > 解决方案 > 有没有办法确定参数是否是 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.stringifyand.toString()但他们似乎只是将 and 的全部内容串起来,collectionfct不是他们的名字。

标签: javascriptmethods

解决方案


利用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);


推荐阅读