如何确定是否定义了JavaScript函数?

ily*_*oli 3 javascript

我想检查函数是否已定义(我不关心如何,我的意思是它是可调用的)

示例代码:

var functions = {
    'alert':'alert',
    'undefinedFunction':'undefinedFunction',
    'ff.showAlert':'ff.showAlert'
};

var ff = {
    showAlert: function() {
        alert('the function works');
    }
};

for (i in functions) {
    console.log(i+' : '+typeof window[functions [i]]);
}
Run Code Online (Sandbox Code Playgroud)

这会返回:

alert : function
undefinedFunction : undefined
ff.showAlert : undefined

console.log(typeof window.ff.showAlert); return function
Run Code Online (Sandbox Code Playgroud)

现场演示
有没有办法以编程方式检查函数是否存在?

Jam*_*mes 6

代码:

window[functions [i]]
Run Code Online (Sandbox Code Playgroud)

正在检查,window['ff.showAlert']但你真正想要检查的是:

window['ff']['showAlert']
Run Code Online (Sandbox Code Playgroud)

要么

window.ff.showAlert
Run Code Online (Sandbox Code Playgroud)

为此,您需要遍历命名空间(window- > ff- > ...):

function methodIsDefined(fn, obj) {
  var ns = fn.split('.');
  fn = ns.pop();
  do {
    if (!ns[0]) {
      return typeof obj[fn] === 'function';
    }
  } while(obj = obj[ns.shift()]);
  return false;
}
Run Code Online (Sandbox Code Playgroud)

例如

methodIsDefined('ff.showAlert', window); // => true
methodIsDefined('ff.foo', window); // => false
Run Code Online (Sandbox Code Playgroud)