介绍

本章介绍 JavaScript 并讨论其一些基本概念。

¥This chapter introduces JavaScript and discusses some of its fundamental concepts.

你应该已经知道的

¥What you should already know

本指南假设你具有以下基本背景:

¥This guide assumes you have the following basic background:

  • 对互联网和万维网 (WWW) 的一般了解。
  • 良好的超文本标记语言 (HTML) 应用知识。
  • 有一定的编程经验。如果你是编程新手,请尝试主页上链接的有关 JavaScript 的教程之一。

在哪里可以找到 JavaScript 信息

¥Where to find JavaScript information

MDN 上的 JavaScript 文档包括以下内容:

¥The JavaScript documentation on MDN includes the following:

如果你是 JavaScript 新手,请从 学习区JavaScript 指南 中的文章开始。一旦你牢牢掌握了基础知识,你就可以使用 JavaScript 参考 来获取有关各个对象和语句的更多详细信息。

¥If you are new to JavaScript, start with the articles in the learning area and the JavaScript Guide. Once you have a firm grasp of the fundamentals, you can use the JavaScript Reference to get more details on individual objects and statements.

什么是 JavaScript?

¥What is JavaScript?

JavaScript 是一种跨平台、面向对象的脚本语言,用于使网页具有交互性(例如,具有复杂的动画、可点击的按钮、弹出菜单等)。还有更高级的 JavaScript 服务器端版本,例如 Node.js,它允许你向网站添加比下载文件更多的功能(例如多台计算机之间的实时协作)。在主机环境(例如,Web 浏览器)内,JavaScript 可以连接到其环境中的对象,以提供对它们的编程控制。

¥JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.js, which allow you to add more functionality to a website than downloading files (such as realtime collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them.

JavaScript 包含一个标准对象库(例如 ArrayDateMath),以及一组核心语言元素(例如运算符、控制结构和语句)。核心 JavaScript 可以通过补充额外的对象来扩展用于各种目的;例如:

¥JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

  • 客户端 JavaScript 通过提供对象来控制浏览器及其文档对象模型 (DOM) 来扩展核心语言。例如,客户端扩展允许应用将元素放置在 HTML 表单上并响应用户事件,例如鼠标单击、表单输入和页面导航。
  • 服务器端 JavaScript 通过提供与在服务器上运行 JavaScript 相关的对象来扩展核心语言。例如,服务器端扩展允许应用与数据库通信,提供从应用的一个调用到另一个调用的信息连续性,或者在服务器上执行文件操作。

这意味着在浏览器中,JavaScript 可以改变网页 (DOM) 的外观。同样,服务器上的 Node.js JavaScript 可以响应浏览器中执行的代码发送的自定义请求。

¥This means that in the browser, JavaScript can change the way the webpage (DOM) looks. And, likewise, Node.js JavaScript on the server can respond to custom requests sent by code executed in the browser.

JavaScript 和 Java

¥JavaScript and Java

JavaScript 和 Java 在某些方面相似,但在其他方面则有根本的不同。JavaScript 语言类似于 Java,但没有 Java 的静态类型和强类型检查。JavaScript 遵循大多数 Java 表达式语法、命名约定和基本控制流结构,这就是它从 LiveScript 重命名为 JavaScript 的原因。

¥JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.

与 Java 通过声明构建的类的编译时系统相比,JavaScript 支持基于少量表示数字、布尔值和字符串值的数据类型的运行时系统。JavaScript 具有基于原型的对象模型,而不是更常见的基于类的对象模型。基于原型的模型提供动态继承;也就是说,继承的内容对于各个对象来说可能会有所不同。JavaScript 还支持没有任何特殊声明要求的函数。函数可以是对象的属性,作为松散类型的方法执行。

¥In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

与 Java 相比,JavaScript 是一种形式非常自由的语言。你不必声明所有变量、类和方法。你不必关心方法是公共的、私有的还是受保护的,也不必实现接口。变量、参数和函数返回类型没有显式类型化。

¥JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

Java 是一种基于类的编程语言,旨在快速执行和类型安全。例如,类型安全意味着你无法将 Java 整数转换为对象引用或通过破坏 Java 字节码来访问私有内存。Java 基于类的模型意味着程序仅由类及其方法组成。Java 的类继承和强类型通常需要紧密耦合的对象层次结构。这些要求使得 Java 编程比 JavaScript 编程更加复杂。

¥Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting the Java bytecode. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

相比之下,JavaScript 的精神源自一系列较小的动态类型语言,例如 HyperTalk 和 dBASE。这些脚本语言为更广泛的受众提供了编程工具,因为它们具有更简单的语法、专门的内置功能以及对对象创建的最低要求。

¥In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

JavaScript Java
面向对象。对象类型之间没有区别。继承是通过原型机制实现的,可以动态地将属性和方法添加到任何对象中。 基于阶级。对象分为类和实例,并通过类层次结构进行所有继承。类和实例不能动态添加属性或方法。
未声明变量数据类型(动态类型、松散类型)。 必须声明变量数据类型(静态类型、强类型)。
无法自动写入硬盘。 可以自动写入硬盘。

JavaScript 和 ECMAScript 规范

¥JavaScript and the ECMAScript specification

JavaScript 在 埃克玛国际 上进行了标准化,埃克玛国际 是欧洲信息和通信系统标准化协会(ECMA 以前是欧洲计算机制造商协会的缩写),旨在提供基于 JavaScript 的标准化国际编程语言。这个 JavaScript 的标准化版本称为 ECMAScript,在支持该标准的所有应用中的行为方式相同。公司可以使用开放标准语言来开发 JavaScript 的实现。ECMAScript 标准记录在 ECMA-262 规范中。

¥JavaScript is standardized at Ecma International — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification.

ECMA-262 标准还被 ISO(国际标准化组织)批准为 ISO-16262。你还可以在 Ecma 国际网站 上找到规范。ECMAScript 规范没有描述由 万维网联盟 (W3C) 和/或 WHATWG(网络超文本应用技术工作组) 标准化的文档对象模型 (DOM)。DOM 定义了向脚本公开 HTML 文档对象的方式。要更好地了解使用 JavaScript 编程时使用的不同技术,请参阅文章 JavaScript 技术概述

¥The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article JavaScript technologies overview.

JavaScript 文档与 ECMAScript 规范

¥JavaScript documentation versus the ECMAScript specification

ECMAScript 规范是一组实现 ECMAScript 的要求。如果你想在 ECMAScript 实现或引擎中实现符合标准的语言功能(例如 Firefox 中的 SpiderMonkey 或 Chrome 中的 V8),它会非常有用。

¥The ECMAScript specification is a set of requirements for implementing ECMAScript. It is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or V8 in Chrome).

ECMAScript 文档并不是为了帮助脚本程序员。编写脚本时请使用 JavaScript 文档获取信息。

¥The ECMAScript document is not intended to help script programmers. Use the JavaScript documentation for information when writing scripts.

ECMAScript 规范使用 JavaScript 程序员可能不熟悉的术语和语法。尽管 ECMAScript 中对语言的描述可能有所不同,但语言本身保持不变。JavaScript 支持 ECMAScript 规范中概述的所有功能。

¥The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.

JavaScript 文档描述了适合 JavaScript 程序员的语言的各个方面。

¥The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

JavaScript 入门

¥Getting started with JavaScript

要开始使用 JavaScript,你只需要一个现代的 Web 浏览器。火狐浏览器Chrome微软 Edge苹果浏览器 的最新版本都支持本指南中讨论的功能。

¥To get started with JavaScript, all you need is a modern web browser. Recent versions of Firefox, Chrome, Microsoft Edge, and Safari all support the features discussed in this guide.

JavaScript 控制台(有时称为 Web 控制台,或简称为控制台)是探索 JavaScript 的一个非常有用的工具:这是一个可以让你输入 JavaScript 并在当前页面运行它的工具。

¥A very useful tool for exploring JavaScript is the JavaScript Console (sometimes called the Web Console, or just the console): this is a tool which enables you to enter JavaScript and run it in the current page.

这里的屏幕截图显示的是 火狐网络控制台,但所有现代浏览器都附带一个以类似方式工作的控制台。

¥The screenshots here show the Firefox Web Console, but all modern browsers ship with a console that works in a similar way.

打开控制台

¥Opening the console

打开控制台的确切说明因浏览器而异:

¥The exact instructions for opening the console vary from one browser to another:

输入并运行 JavaScript

¥Entering and running JavaScript

控制台出现在浏览器窗口的底部。控制台底部有一条输入行,你可以使用它输入 JavaScript,输出将显示在上面的面板中:

¥The console appears at the bottom of the browser window. Along the bottom of the console is an input line that you can use to enter JavaScript, and the output appears in the panel above:

A browser window with the web console open at the bottom, containing two lines of input and output. Text can be entered below that.

控制台的工作方式与 eval 完全相同:返回最后输入的表达式。为了简单起见,可以想象,每次在控制台中输入一些内容时,它实际上都被 console.log 包围在 eval 周围,如下所示:

¥The console works the exact same way as eval: the last expression entered is returned. For the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by console.log around eval, like so:

js
console.log(eval("3 + 5"));

控制台多行输入

¥Multi-line input in the console

默认情况下,如果你在输入一行代码后按 Enter(或 Return,具体取决于你的键盘),则会执行你键入的字符串。要输入多行输入:

¥By default, if you press Enter (or Return, depending on your keyboard) after entering a line of code, then the string you typed is executed. To enter multi-line input:

  • 如果你输入的字符串不完整(例如,你输入了 function foo() {),那么控制台会将 Enter 视为换行符,并让你输入另一行。
  • 如果你在按住 Shift 的同时按 Enter,那么控制台会将其视为换行符,并让你键入另一行。
  • 仅在 Firefox 中,你可以激活 多行输入模式,在其中你可以在迷你编辑器中输入多行,然后在准备好时运行整个过程。

要开始编写 JavaScript,请打开控制台,复制以下代码,然后将其粘贴到提示符处:

¥To get started with writing JavaScript, open the console, copy the following code, and paste it in at the prompt:

js
(function () {
  "use strict";
  /* Start of your code */
  function greetMe(yourName) {
    alert(`Hello ${yourName}`);
  }

  greetMe("World");
  /* End of your code */
})();

Enter 即可在浏览器中观看它的展开!

¥Press Enter to watch it unfold in your browser!

下一步是什么

¥What's next

在接下来的几页中,本指南向你介绍 JavaScript 语法和语言功能,以便你能够编写更复杂的应用。

¥In the following pages, this guide introduces you to the JavaScript syntax and language features, so that you will be able to write more complex applications.

但现在,请记住始终在代码之前包含 (function(){"use strict";,并将 })(); 添加到代码末尾。严格模式IIFE 文章解释了它们的作用,但目前可以将它们视为执行以下操作:

¥But for now, remember to always include the (function(){"use strict"; before your code, and add })(); to the end of your code. The strict mode and IIFE articles explain what those do, but for now they can be thought of as doing the following:

  1. 防止 JavaScript 中的语义给初学者带来麻烦。
  2. 防止在控制台中执行的代码片段相互交互(例如,在一个控制台执行中创建的某些内容用于不同的控制台执行)。