JavaScript 原始值和引用值

216 阅读2分钟

在 JavaScript 中,变量可以存在两种类型的值,即原始值和引用值。

原始值(值类型)

存储在栈(stack)中的简单数据段,也就是说,它们的值直接存储在变量访问的位置。类型包括:Undefined、null、Boolean、Number、String 以及 Symble。

  • 占用内存空间大小固定
  • 保存与复制的是值本身
  • 使用 typeof 检测数据类型

引用值(引用类型)

存储在堆(heap)中的对象,也就是说,存储在变量处的值是一个指针(point),指向存储对象的内存处。类型包括:Object、Array、Date、Regexp、Function、基本包装类型及单体内置对象。

其中基本包装类型,包括:Boolean 类型、Number 类型、String 类型。单体内置对象,包括:Global 对象和 Math 对象。

  • 占用内存空间大小不固定
  • 保存与复制的是指向堆内存的栈内存中的指针
  • 使用 instanceof 检测数据类型

举例:

// 值类型 
let a = true;
let b = a;

console.log(a, b); // true true
b = false;
console.log(a); // true
// 保存与复制的是值本身,当执行 let b = a; 时,a = true 和 b = true 是完全独立的,所以修改 b = false,不会影响 a 的值


// 引用类型
const obj = {
  name: 'Jack',
  age: 18
}
const obj2 = obj;

console.log(obj, obj2); // {name: 'Jack', age: 18, name: 'Jack', age: 18}
obj2.name = 'Austin';
console.log(obj, obj2); // {name: 'Austin', age: 18, name: 'Austin', age: 18}
// 保存与复制的是指向堆内存的栈内存中的指针,obj 和 obj2 是两个不同的存储在栈内存中的指针,但同时指向了堆内存中的同一个对象



// 类型检测
const isNum = 10;
console.log(typeof isNum); // number

const isBoolean = true;
console.log(typeof isBoolean); // boolean

const isUndifined = undefined;
console.log(typeof isUndifined); // undefined

const isString = '字符串';
console.log(typeof isString); // string

const isSymble = Symbol('abc');
console.log(typeof isSymble); // symble

const isNull = null;
console.log(typeof isNull); // object,返回 object 是因为:null 是一个只有一个值的特殊类型,表示一个空对象引用

// 除去 function 类型之外,其他引用类型使用 typeof 检测均返回 object
// 所以检测引用类型数据,不能使用typeof,需要使用 instanceof  
console.log( typeof function(){}, typeof {},  typeof [], typeof new Date(), typeof new Boolean(true), typeof new RegExp("\\w+")) // function object object object object object
console.log({} instanceof Object, [] instanceof Array) // true true