My Code
There’s a small CoffeScript code snipped:
Function::trigger = (prop, getter, setter) ->
Object.defineProperty this.prototype
get: getter,
set: setter
The JavaScript Compilation
The compiler outputs:
Function.prototype.trigger = function(prop, getter, setter) {
Object.defineProperty(this.prototype({
get: getter
}));
return {
set: setter
};
};
But I want the output to be:
Function.prototype.trigger = function(prop, getter, setter) {
Object.defineProperty(this.prototype({
get: getter
set: setter
};
};
My Questions
- Why does the compiler output something that strange?
- How can I change my code in order to get the compiler to output what I want?
Thanks.
Your indentation is wrong. Also notice how you forgot the comma after this.prototype, this is making the CoffeeScript compiler think you’re trying to execute the function named this.prototype with an object as an argument.
The above code should look like this. Please note that I made some changes to make it more “CoffeeScript-like” 🙂
Remember, CoffeeScript is whitespace-significant. CoffeeScript also removes a lot of the “fluff” you see in JavaScript (commas, parens, curly braces, etc). Because of this, formatting your code to comply with CoffeeScript standards is vital to writing code that compiles how you expect. If you don’t, the compiler will be forced to make guesses as to what you were trying to do, and it’s often wrong.
The above example correctly compiles to the following JavaScript (based on coffeescript.org)…
Please note that CoffeeScript will automatically return the last executed expression (in this case, the call to Object.defineProperty). If you want to avoid this behavior (you shouldn’t, but sometimes you need to) you can just add a return statement at the end of your Function.prototype.trigger function, as such:
Which will compile to…