JS typeof fn = = = 'function' fn of
- 2021-08-06 20:42:12
- OfStack
When I was looking at other people's code, I saw that the code was written like this
function(){
fn & & fn()
}
It probably means this, but I feel that it seems meaningless to write like this. Can you give me some advice?
If fn does not exist, do nothing and report no errors. If fn exists, try to execute fn
1 Generally speaking, fn & & fn () looks like the following statement
if (fn) {
fn()
}
1 Generally speaking, the dynamic call of a function, because you don't know that this function exists.
For the most part this means that fn () is not executed if fn is undefined. React would say this for optional and callback.
In js, this is standard. Greatly reduce the amount of code, which is more direct than 3-mesh operation. Other languages are similar: fn? . xx ()
This is the right idea, the implementation is wrong, fn may exist, but it may not be function, and it will be wrong to execute fn () 1.
Share the correct writing below
typeof fn === "function" & & fn()
Practical application
function addScript (url, fn) {
var script = document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', url)
script.setAttribute('async', 'async')
document.getElementsByTagName('head')[0].appendChild(script)
script.onload = function () {
typeof fn === 'function' && fn()
}
}
Summary
The correct way to write it is this: typeof (fn) = = = 'function' & & fn (), but fn is generally agreed upon & & fn () transitive 1 must be a function
This is the magic of the js logical operator:
When multiple
&
&
When concatenated, the expression to the first truthy is executed;
When a plurality of them are concatenated, the expression to the first false-thy is executed;
However, I agree with Wang Yin's blog that short-circuit mechanism is to optimize the execution efficiency of programs, not to show off programmers' skills.
See this article for more:
Is it? . Operator, excluding square brackets, I put quotation marks into square brackets.
See here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
You can choose Simplified Chinese when entering.