UNPKG

sai-language

Version:

An object-oriented language designed to afford code comprehension and maintenance. Transpiles in-place to Javascript.

84 lines (45 loc) 2.38 kB
## Function Parameters There are two schools of thought on passing function parameters. The first you are probably more familiar with, where parameters must all be included in order. This is the standard approach in Javascript. The second is passing parameters by name. This is less familiar. There are advantages to both methods, and disadvantages. You may choose to create functions that operate either way, but you must always call them consistently -- a function with named parameters can't be called without naming the parameters. #### Parameters by Order // define a function set ByOrder task given first, second, third debug first + second + third // call it ByOrder "a", "b", "c" // results > abc In Javascript, this looks like the following: var ByOrder = function(first, second, third) { console.log(first+second+third); } ByOrder("a","b","c"); > abc #### Parameters by Name // define a function set ByName task debug $first + $second + $third // call it // note the colon after the verb ByName: first 'a', second 'b', third 'c' > abc In Javascript: var ByName = function(p) { console.log(p.first+p.second+p.third); } ByName({first:'a', second:'b', third:'c'}); > abc ### What's happening? When you call a function passing parameters by name, you're passing in an object with those parameters as attributes. Looking closely at the parameter-by-name invocation, the colon signals the beginning of a structure definition. On the other side, in a function called with named parameters, the __$__ scoping prefix means look up the named attribute in the first parameter passed in on the function call. ### What's the point? Passing a single object, with named attributes, instead of a sequence of values, gives you different ways of approaching code design. In particular, because named parameters are passed as an object, that object can be re-used from call to call. As well, attributes in that object can be changed, or return values set givenparameters within the object. #### Parameter/Object re-use set parameters: first 'a', second 'b', third 'c' ByName parameters > abc set parameters.third d ByName parameters > abd