Alert function not working in coffeescript

穿精又带淫゛_ 提交于 2019-12-24 07:03:13

问题


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.



来源:https://stackoverflow.com/questions/44389540/alert-function-not-working-in-coffeescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!