2

在咖啡脚本中,在函数上使用存在运算符,如下所示:

myFunc?()

编译为

typeof myFunc === "function" ? myFunc() : void 0;

有没有办法优雅地定义代替“void 0”的内容?还是我必须全部写出来而不是使用原始符号?

4

1 回答 1

8

您可以添加另一个存在运算符:

x = f?() ? 'pancakes'

如果返回,那将不起作用,或者如果f()返回,它将做正确的事情。例如:nullundefinedf()false

f = 'not a function'
console.log f?() ? 'pancakes'
# pancakes

f = -> 'is a function'
console.log f?() ? 'pancakes'
# is a function

f = -> null
console.log f?() ? 'pancakes'
# pancakes

f = ->
console.log f?() ? 'pancakes'
# pancakes

f = -> false
console.log f?() ? 'pancakes'
# false

演示:http: //jsfiddle.net/ambiguous/f6yvN/1/

所以你可以接近你想要的,这可能足够接近,这取决于你期望函数返回什么样的东西。

于 2012-04-16T04:37:21.023 回答