我有一个变量,如果该变量是一个对象,我想在该对象上调用一个方法,如果不是,我什么也不想做。
我想知道是否有任何理由不应该这样做。
var foo = null;
////////////////////////////////////////////////
// some code that could change foo to a object
////////////////////////////////////////////////
foo && foo.bar();
最佳答案
使用 ES6,您可以组合 optional chaining operator与 call :
foo?.bar?.call()
如果要传递参数,请记住 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">
关于如果对象存在,则调用方法的 Javascript 速记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644222/