警报功能在 coffeescript 中不起作用

Alert function not working in coffeescript

我在博客中发现了 CoffeeScript 并决定尝试一下,我的第一个 project/code 是这个

alert "Hello CoffeeScript!"

无效,给出此回复

ReferenceError: alert is not defined

我做错了什么吗?

window.alert 是由 DOM(在浏览器中)定义的方法,而不是由 Javascript 定义的方法。如果您 运行 所在的环境没有定义全局 alert 方法,则您无法调用它。

JavaScript 是一种与环境 的概念密切相关的语言。 浏览器Node.js 是 运行 JS 代码的两种可能环境(CoffeeScript 编译为 JavaScript) .

当 JavaScript 嵌入浏览器时,全局对象为 window。但是在 Node.js 中,全局对象只是 global.

某些方法在两种环境中都可用,例如核心 JavaScript 方法...

  • String.prototype 方法
  • Array.prototype 方法
  • Object.prototype 方法
  • 等等

... 以及特定的 window 方法,例如 setIntervalsetTimeout.

但是,window.alert在CLI中显然是不可用的。如果你想在 Node 中使用这个功能,你将不得不使用像 alert-node ---> npm i alert-node.

这样的东西

JavaScript

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

命令: node alert.js

CoffeeScript

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

命令: coffee alert.coffee