Alert function not working in coffeescript

2019-08-17 06:34发布

问题:

I found about CoffeeScript in a blog and decided to give it a try ,my first project/code with it was this

alert "Hello CoffeeScript!"

It doesn't work and gives this reply

ReferenceError: alert is not defined

is there anything i am doing wrong?

回答1:

JavaScript is a language which is strongly tied to the concept of environments. A browser and Node.js are two possible environments to run JS code (CoffeeScript compiles to JavaScript).

When JavaScript is embedded in a browser, the global object is window. But in Node.js, the global object is simply global.

Some methods are available in both environments, like core JavaScript methods...

  • String.prototype methods
  • Array.prototype methods
  • Object.prototype methods
  • etc.

... and specific window methods like setInterval or setTimeout.

However, window.alert is obviously not available in CLI. If you want this functionality in Node, you will have to use something like alert-node ---> npm i alert-node.

JavaScript

// alert.js
var alert = require('alert-node');
alert('Hello');

Command: node alert.js

CoffeeScript

# alert.coffee
alert = require 'alert-node'
alert 'Hello'

Command: coffee alert.coffee



回答2:

window.alert is a method defined by the DOM (in browsers), not by Javascript. If the environment you're running this in doesn't have a global alert method defined, then you can't call it.