这是用户在 2024-5-24 17:08 为 https://justjavascript.com/the-javascript-universe 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
Skip to content

The JavaScript Universe

Dan Abramov
Dan Abramov
episode 02

In the beginning was the Value.

What is a value? It’s hard to say.

What is a point in geometry? What is a word in human language? A value is a fundamental concept in JavaScript—so we can’t define it through other terms.
什么是几何中的点?什么是人类语言中的词?在 JavaScript 中,值是一个基本概念——因此我们无法通过其他术语来定义它。

Instead, we’ll define it through examples. Numbers and strings are values. Objects and functions are values, too.

There are also a lot of things that are not values, like the pieces of our code—our if statements, loops, and variable declarations, for example.
还有很多东西不是值,比如我们的代码片段——我们的 if 语句、循环和变量声明等。

Values and Code 值和代码

As we start building our mental model, one of the first common misconceptions we need to clear up is that values are our code. Instead, we need to think of them separately—our code interacts with values, but values exist in a completely separate space.

To distinguish between values and code in my JavaScript program, I like to imagine this drawing of the Little Prince by Antoine de Saint-Exupéry:
为了在我的 JavaScript 程序中区分值和代码,我喜欢想象安托万·德·圣-埃克苏佩里画的小王子这幅画:

I’m standing on a small planet, holding a list of instructions. This list is my program—my code. As I read through my list of instructions, I can see a lot going on—there are if statements, variable declarations, commas and curly braces.
我站在一个小星球上,手里拿着一份指令清单。这份清单就是我的程序——我的代码。当我阅读我的指令清单时,我可以看到很多内容——有 if 语句、变量声明、逗号和大括号。

My code contains instructions like “make a function call,” “do this thing many times,” or even “throw an error.” I read through these instructions step by step from the surface of my little world.

But every once in a while, I look up.

On a clear night, I see the different values in the JavaScript sky: booleans, numbers, strings, symbols, functions and objects, null and undefined—oh my! I might refer to them in my code, but they don’t exist inside my code.
在一个晴朗的夜晚,我看到 JavaScript 天空中的不同值:布尔值、数字、字符串、符号、函数和对象, nullundefined ——天哪!我可能会在我的代码中引用它们,但它们并不存在于我的代码中。

In our JavaScript universe, values float in space.
在我们的 JavaScript 宇宙中,值漂浮在空间中。

“Hold on,“ you might say, “I always thought of values as being inside of my code!” Here, I’m asking you to take a leap of faith. It will take a few more modules for this mental model to pay off. Give it five minutes. I know what I’m doing.

Values 价值

Broadly, there are two kinds of values.

Primitive Values 原始值

Primitive values are like stars—cold and distant, but always there when I need them. Even from the surface of my small planet, I can find them and point them out. They can be numbers and strings, among other things. All primitive values have something in common: They are a permanent part of our JavaScript universe. I can point to them, but I can’t create, destroy, or change them.
原始值就像星星——寒冷而遥远,但总是在我需要它们的时候出现。即使在我这个小星球的表面,我也能找到它们并指出它们。它们可以是数字和字符串,等等。所有原始值都有一个共同点:它们是我们 JavaScript 宇宙的永久部分。我可以指向它们,但不能创建、销毁或更改它们。

To see primitive values in practice, open your browser’s console and log them:


Objects and Functions 对象和函数

Objects and functions are also values but, unlike primitive values, I can manipulate them from my code. If primitive values are like distant stars, then objects and functions are more like asteroids floating around my planet. They’re not part of my code, but they’re close enough to manipulate.

Fun Fact 有趣的事实

Functions are objects, but because they include a few unique additional features, we’re going to refer to them separately to avoid confusion.

Go ahead and log a few of them to the browser console:

console.log((x) => x * 2);

Notice how the browser console displays them differently from primitive values. Some browsers might display an arrow before them, or do something special when you click them. If you have a few different browsers installed, compare how they visualize objects and functions.

Types of Values 值的类型

At first, all values in the JavaScript cosmos might look the same—just bright dots in the sky. But we are here to study all of the different things floating above us in our JavaScript universe, so we’ll need a way to categorize them.
起初,JavaScript 宇宙中的所有值看起来可能都一样——只是天空中的亮点。但我们在这里是为了研究我们 JavaScript 宇宙中漂浮的所有不同事物,所以我们需要一种方法来对它们进行分类。

We can break values down into types—values of the same type behave in similar ways. As an aspiring astronomer, you might want to know about every type of value that can be observed in the JavaScript sky.
我们可以将值分解为类型——相同类型的值以类似的方式表现。作为一个有抱负的天文学家,你可能想知道在 JavaScript 天空中可以观察到的每种类型的值。

After almost twenty-five years of studying JavaScript, the scientists have only discovered nine such types:

Primitive Values 原始值

  • Undefined (undefined), used for unintentionally missing values.
    未定义 ( undefined ),用于无意中缺失的值。
  • Null (null), used for intentionally missing values.
    空 ( null ),用于有意缺失的值。
  • Booleans (true and false), used for logical operations.
    布尔值( truefalse ),用于逻辑运算。
  • Numbers (-100, 3.14, and others), used for math calculations.
    数字( -1003.14 和其他),用于数学计算。
  • BigInts (uncommon and new), used for math on big numbers.
  • Strings ("hello", "abracadabra", and others), used for text.
    字符串( "hello""abracadabra" ,以及其他),用于文本。
  • Symbols (uncommon), used to perform rituals and hide secrets.

Objects and Functions 对象和函数

  • Objects ({} and others), used to group related data and code.
    对象( {} 及其他),用于分组相关数据和代码。
  • Functions (x => x * 2 and others), used to refer to code.
    函数( x => x * 2 和其他),用于指代代码。

No Other Types 没有其他类型

You might ask: “But what about other types I have used, like arrays?”

In JavaScript, there are no other fundamental value types other than the ones we have just enumerated. The rest are all objects! For example, even arrays, dates, and regular expressions fundamentally are objects in JavaScript:
在 JavaScript 中,除了我们刚刚列举的那些基本值类型之外,没有其他的基本值类型。其它的都是对象! 例如,即使是数组、日期和正则表达式从根本上来说也是 JavaScript 中的对象:

console.log(typeof []); // "object"
console.log(typeof new Date()); // "object"
console.log(typeof /(hello|goodbye)/); // "object"
Fun Fact 有趣的事实

“I see,” you might reply, “this is because everything is an object!” Alas, this is a popular urban legend, but it’s not true.

Although code like "hi".toUpperCase() makes "hi" seem like an object, this is nothing but an illusion. JavaScript creates a temporary object when you do this, and then immediately discards it. It’s fine if this mechanism doesn’t click for you yet. It is indeed rather confusing!
虽然像 "hi".toUpperCase() 这样的代码使 "hi" 看起来像一个对象,但这只是一个幻觉。JavaScript 在你这样做的时候创建了一个临时对象,然后立即将其丢弃。如果这个机制还没有让你理解,那也没关系。这确实相当令人困惑!

For now, you only need to remember that primitive values, such as numbers and strings, are not objects.

Checking a Type 检查类型

There are only nine types of values, but how do we know a particular value’s type?

If we want to check a value’s type, we can ask with the typeof operator. Below are a few examples you can try in the browser console:
如果我们想检查一个值的类型,可以使用 typeof 运算符。以下是一些可以在浏览器控制台中尝试的示例:

console.log(typeof 2); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof undefined); // "undefined"

Strictly speaking, using parens isn’t required with typeof. For example, typeof 2 would work just as fine as typeof(2). However, sometimes parens are required to avoid an ambiguity. One of the cases below would break if we omitted the parens after typeof. Try to guess which one it is:
严格来说,使用括号并不是 typeof 的必要条件。例如, typeof 2typeof(2) 一样好用。然而,有时为了避免歧义需要使用括号。以下案例之一在省略 typeof 后的括号时会出错。猜猜是哪一个:

console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof ((x) => x * 2)); // "function"

You can verify your guess in the browser console.

You might have questions. Good. If you ask a question, our JavaScript universe might answer it! Provided, of course, that you know how to ask.
你可能会有问题。很好。如果你问一个问题,我们的 JavaScript 宇宙可能会回答你!当然,前提是你知道如何提问。

Expressions 表达式

There are many questions JavaScript can’t answer. If you want to know whether it’s better to confess your true feelings to your best friend or to keep waiting until you both turn into skeletons, JavaScript won’t be of much help.
有很多问题是 JavaScript 无法回答的。如果你想知道是否该向你最好的朋友坦白你的真实感情,或者继续等待直到你们都变成骷髅,JavaScript 也无能为力。

But there are some questions that JavaScript would be delighted to answer. These questions have a special name—they are called expressions.
但是有一些问题,JavaScript 会很乐意回答。这些问题有一个特殊的名字——它们被称为表达式。

If we “ask” the expression 2 + 2, JavaScript will “answer” with the value 4.
如果我们“询问”表达式 2 + 2 ,JavaScript 会用值 4 “回答”。

console.log(2 + 2); // 4

For another example, remember how we determined the type of a value with typeof. In fact, that was also an expression! Our “question” was typeof(2) and the JavaScript universe answered it with the string value "number".
再举一个例子,记得我们如何用 typeof 确定一个值的类型。事实上,那也是一个表达式!我们的“问题”是 typeof(2) ,JavaScript 宇宙用字符串值 "number" 回答了它。

console.log(typeof 2); // "number"

Expressions are questions that JavaScript can answer. JavaScript answers expressions in the only way it knows how—with values.
表达式是 JavaScript 可以回答的问题。JavaScript 用它唯一知道的方式来回答表达式——用值。

If the word “expression” confuses you, think of it as a piece of code that expresses a value. You might hear people say that 2 + 2 “results in” or “evaluates to” 4. These are all different ways to say the same thing.
如果“表达式”这个词让你感到困惑,把它想象成表达一个值的代码片段。你可能会听到人们说 2 + 2 “结果是”或“计算为” 4 。这些都是表达同一个意思的不同方式。

We ask JavaScript 2 + 2, and it answers with 4. Expressions always result in a single value. Now we know enough about expressions to be dangerous!
我们问 JavaScript 2 + 2 ,它用 4 回答我们。表达式总是得到单一的值。现在我们对表达式有足够的了解,可以无所畏惧了!

Recap 回顾

Let’s recap what we know so far:

  1. There are values, and then there’s code. We can think of values as different things “floating” in our JavaScript universe. They don’t exist inside our code, but we can refer to them from our code.
    有值,然后有代码。我们可以将值视为在我们的 JavaScript 宇宙中“漂浮”的不同事物。它们不存在于我们的代码中,但我们可以从代码中引用它们。
  2. There are two categories of values: there are Primitive Values, and then there are Objects and Functions. In total, there are nine separate types. Each type serves a specific purpose, but some are rarely used.
  3. Some values are lonely. For example, null is the only value of the Null type, and undefined is the only value of the Undefined type. As we will learn later, these two lonely values are quite the troublemakers!
    有些值是孤独的。例如, null 是 Null 类型的唯一值,而 undefined 是 Undefined 类型的唯一值。正如我们稍后将了解到的,这两个孤独的值是相当麻烦的!
  4. We can ask questions with expressions. Expressions exist in our code, so they are not values. Rather, JavaScript will answer our expressions with values. For example, the 2 + 2 expression is answered with the value 4.
    我们可以用表达式来提问。表达式存在于我们的代码中,所以它们不是值。相反,JavaScript 会用值来回答我们的表达式。例如, 2 + 2 表达式的答案是值 4
  5. We can inspect the type of something by wrapping it in a typeof expression. For example, typeof(4) results in the string value "number".
    我们可以通过将某物包装在 typeof 表达式中来检查其类型。例如, typeof(4) 会产生字符串值 "number"

These might seem like small steps, but we’re laying the foundation for everything else to come. We’re building our JavaScript universe, together. There are 9 more chapters with exercises for you to practice.
这些步骤看起来可能很小,但我们正在为接下来的一切奠定基础。我们正在一起构建我们的 JavaScript 宇宙。还有 9 章练习供你练习。

Ready for more? 准备好迎接更多挑战了吗?

Just JavaScript is my distilled mental model of how JavaScript works and a collaboration with Maggie Appleton.
纯粹的 JavaScript 是我对 JavaScript 工作原理的提炼心智模型,并与 Maggie Appleton 合作完成。

a crystal ball
yours forever 永远属于你

Includes all 10 episodes + quiz exercises.
包括所有 10 集+测验练习。

  • Mental Models ・心理模型
  • The JavaScript Universe ・JavaScript 宇宙
  • Values and Variables ・数值和变量
  • Studying from the Inside
  • Meeting the Primitive Values
  • Meeting Objects and Functions
  • Equality of Values ・值的相等性
  • Properties ・属性
  • Mutation ・突变
  • Prototypes ・原型
30 day money back guarantee
30 天退款保证