Brackets in CoffeeScript format

I am just learning CoffeeScript, and I'm trying to do something that I would normally do in plain JavaScript.

Here is what I tried to do:

initializeWebGL = (canvas) ->
    gl = canvas.getContext "webgl" or canvas.getContext "experimental-webgl"

Which compiles what I expect:

var initializeWebGL;

initializeWebGL = function(canvas) {
  var gl;
  return gl = canvas.getContext("webgl" || canvas.getContext("experimental-webgl"));
};

To get what I really want, I need to enclose the arguments getContextin parentheses:

initializeWebGL = (canvas) ->
    gl = canvas.getContext("webgl") or canvas.getContext("experimental-webgl")

Which creates what I want:

var initializeWebGL;

initializeWebGL = function(canvas) {
  var gl;
  return gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
};

Is there a better way to do what I'm trying to achieve than just adding parentheses around function calls, as in the second example?

+4
source share
2 answers

Is there a better way to do what I'm trying to achieve than just adding parentheses around function calls, as in the second example?

No, I do not think so. My rule of thumb is OK to omit the brackets when the function call and its arguments are the last on the line, otherwise include them.

Ok

someFunction 1, 2, 3

Out of order

someFunction 1, someOtherFunction 2, 3

, , . , , .

+5

, , - :

initializeWebGL = (canvas) ->
  gl = canvas.getContext "webgl"
  gl = gl or canvas.getContext "experimental-webgl"

, :

initializeWebGL = (canvas) ->
  gl = canvas.getContext "webgl"
  if !gl? then gl = canvas.getContext "experimental-webgl"
+3

All Articles