JavaScript中的原始类型与对象

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:

假设我们想将caranotherCar进行比较:

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值