简体   繁体   English

如果对象存在则调用方法的Javascript简写

[英]Javascript shorthand to call method if object exists

I have a variable and if that variable is a object I would like to call a method on that object, if not I want to do nothing.我有一个变量,如果该变量是一个对象,我想在该对象上调用一个方法,否则我什么都不做。

I'm wondering if there is any reason why I shouldn't do it like this.我想知道是否有任何理由为什么我不应该这样做。

var foo = null;

  ////////////////////////////////////////////////
  // some code that could change foo to a object
  ////////////////////////////////////////////////

 foo && foo.bar();

With ES6, you can combine optional chaining operator with call :使用 ES6,您可以将可选链运算符call结合使用:

foo?.bar?.call()

If you want to pass arguments, keep in mind that the first one in call assigns this in function call如果要传递参数,请记住调用中的第一个在函数调用中分配this

 var foo = { bar: function(x) { return x; } }; first.value = foo?.bar?.call(0,42); // 42 second.value = foo?.baz?.call(0,42); // undefined, no error
 <input id="first"> <input id="second">

The quick answer is yes, foo && foo.bar() won't throw an exception if foo is null , and if foo is non-null, bar() will be evaluated, and it's value will be the value of the expression.快速回答是肯定的,如果foonull ,则foo && foo.bar()不会抛出异常,如果foo为非空,则bar()将被评估,它的值将是表达式的值。

Longer answer is that any value can be interpreted as a boolean, in the sense that every value is either truthy or falsey, and that the boolean operators do short-circuit evaluation -- left to right, if we see a false && or a true ||更长的答案是,任何值都可以解释为布尔值,因为每个值要么是真值要么是假值,并且布尔运算符进行短路评估——从左到右,如果我们看到一个false &&或一个true || , there's no reason to carry on evaluating. ,没有理由继续评估。

One last fact is that the value of boolean expression is the value of the expression where the short-circuit happened.最后一个事实是布尔表达式的值是发生短路的表达式的值。

You need to assign an object to foo and a property with a function.您需要为foo分配一个对象和一个带有函数的属性。

 var foo; foo = {}; foo.bar = function () { console.log('inside bar'); }; foo && foo.bar && foo.bar();

((typeof foo === 'object') && foo.bar())

or

(!(typeof foo == 'object') || foo.bar())

If foo is of type object then execute.如果 foo 是 object 类型,则执行。

See my answer here javascript using or operator to iterate over list of strings aswell.在这里查看我的回答javascript using or 运算符来迭代字符串列表

This is a "common" issue for unintended behavior, if some uses assignments inside such a sequence and forgets that evaluation stops in the ||这是意外行为的“常见”问题,如果某些人在这样的序列中使用赋值并忘记评估在||停止sequence after first true , or stops after first false in the && .在第一个 true 之后的序列,或者在&&第一个 false 之后停止。

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

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