First, let’s define what are primitive types.
首先,让我们定义什么是基本类型。
Primitive types in JavaScript are
JavaScript中的原始类型是
- strings 弦
- numbers (Number and BigInt) 数字(Number和BigInt)
- booleans (true or false) 布尔值(对或错)
- undefined 未定义
- Symbol values 符号值
null
is a special primitive type. If you run typeof null
you’ll get 'object'
back, but it’s actually a primitive type.
null
是一种特殊的原始类型。 如果您运行typeof null
您将获得'object'
,但这实际上是原始类型。
Everything that is not a primitive type is an object.
不是基本类型的一切都是对象 。
Functions are objects, too. We can set properties and method on functions. typeof
will return 'function'
but the Function constructor derives from the Object constructor.
功能也是对象。 我们可以在函数上设置属性和方法。 typeof
将返回'function'
但Function构造函数是从Object构造函数派生的。
The big differences between primitive types and objects are
基本类型和对象之间的最大区别是
- primitive types are immutable, objects only have an immutable reference, but their value can change over time 基本类型是不可变的,对象仅具有不可变的引用,但其值会随着时间而变化
- primitive types are passed by value. Objects are passed by reference 基本类型按值传递。 对象通过引用传递
- primitive types are copied by value. Objects are copied by reference 基本类型按值复制。 通过引用复制对象
- primitive types are compared by value. Objects are compared by reference 基本类型按值进行比较。 通过引用比较对象
If we copy a primitive type in this way:
如果我们以这种方式复制原始类型:
let name = 'Flavio'
let secondName = name
Now we can change the name
variable assigning it a new value, but secondName
still holds the old value, because it was copied by value:
现在我们可以更改name
变量, secondName
分配一个新值,但是secondName
仍保留旧值,因为它是按值复制的:
name = 'Roger'
secondName //'Flavio'
If we have an object:
如果我们有一个对象:
let car = {
color : 'yellow'
}
and we copy it to another variable:
然后将其复制到另一个变量:
let car = {
color : 'yellow'
}
let anotherCar = car
in this case anotherCar
points to the same object as car
. If you set
在这种情况下, anotherCar
指向与car
相同的对象。 如果您设定
car . color = 'blue'
also
也
anotherCar . color
will be 'blue'
.
将为'blue'
。
The same works for passing around objects to functions, and for comparing.
将对象传递到函数以及进行比较的工作原理相同。
Say we want to compare car
to anotherCar
:
假设我们想将car
与anotherCar
进行比较:
anotherCar === car //true
This is true because both variables point to exactly the same object.
这是正确的,因为两个变量都指向完全相同的对象。
But if anotherCar
was an object with the same properties as car
, comparing them would give a false
result:
但是,如果anotherCar
是具有与car
相同属性的对象,则将它们进行比较将得出false
结果:
let car = {
color : 'yellow'
}
let anotherCar = {
color : 'yellow'
}
anotherCar === car //false
翻译自: https://flaviocopes.com/difference-primitive-types-objects/