简体   繁体   English

从变量内联JavaScript函数调用

[英]Inline javascript function call from variable

I want to call a function inline from a variable, but respecting the case, when the variable is null / undefined or not a function. 我想从一个变量内联调用一个函数,但是要尊重这种情况,当变量为null / undefined或不是一个函数时。

var f;
if(typeof(f) == 'function') {
    f(); // don't get executed
}
f(); // this is of course not working, but it is executing

var fn = function() { console.warn('fn'); }
fn(); // working because fn is a function

Basically I want the if statement, with checking whether the variable is a function or not in one line. 基本上,我需要if语句,并在一行中检查变量是否为函数。

I saw this and thought there has to something for undefined / non functions: 我看到了这一点,并认为对于未定义/非函数有一些要求:

var screenSize = screen.width || 1024;

You can use a logical AND: 您可以使用逻辑AND:

typeof f === 'function' && f();

The second operator is only evaluated if the first one is truish. 仅当第一个算子是truish时才评估第二个算子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM