Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling coffeescript functions from console

Playing a little with coffeescript and Rails 3.1.0.rc4. Have this code:

yourMom = (location) ->
  console.log location

yourMom "wuz hur"

When the page loads, this outputs "wuz hur" properly. But when I try to call

yourMom("wuz hur")

from the chrome js console (as I do sometimes to test normal JS functions), I get a "ReferenceError: yourMom is not defined"

Are functions generated by coffeescript available in this way?

like image 257
Lee Quarella Avatar asked Jul 20 '11 01:07

Lee Quarella


People also ask

How do you call a function in CoffeeScript?

You can simply invoke a function by placing parenthesis after its name as shown in the following example. // Generated by CoffeeScript 1.10. 0 (function() { var add; add = function() { var a, b, c; a = 20; b = 30; c = a + b; return console. log("Sum of the two numbers is: " + c); }; add(); }).

Is CoffeeScript better than JavaScript?

Easy Maintenance and Readability: It becomes easy to maintain programs written in CoffeeScript.It provides the concept of aliases for mostly operators that makes the code more readable.

How do I use CoffeeScript in HTML?

You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file. In other cases, I've seen people use the attributes of type="coffeescript" and type="coffee" , so they might work for you as well. Save this answer.

Is CoffeeScript still used?

In ES6, JavaScript also added many powerful new features and also had a larger community. As of today, January 2021, CoffeeScript is almost dead on the market.


2 Answers

an easier way to share global methods/variables is to use @ which means this.

@yourMom = (location) ->
  console.log location

yourMom "wuz hur"

Nicer syntax and easier to read, but I don't encourage you to create global methods/variables

like image 99
Sébastien Gruhier Avatar answered Oct 01 '22 19:10

Sébastien Gruhier


This happens because coffeescript wraps everything in a closure. The JavaScript output of that code is actually:

(function() {
  var yourMom;
  yourMom = function(location) {
    return console.log(location);
  };
  yourMom("wuz hur");
}).call(this);

If you want to export it to the global scope, you can either do:

window.yourMom = yourMom = (location) ->
  console.log location

or

this.yourMom = yourMom = (location) ->
  console.log location
like image 13
Jamie Wong Avatar answered Oct 01 '22 17:10

Jamie Wong