js 的值类型和引用类型

262 阅读1分钟

1、值类型和引用类型

  • 值类型:
    • 字符串(string)、数值(number)、布尔值(boolean)、none、undefined。
    • 这些类型在赋值的时候,是存在栈内存(大小固定且位置连续的存储空间)中的,即,可以直接访问这些类型的值。可以使用typeof直接判断数据的类型。
  • 引用类型:
    • 对象(Object)、数组(Array)、函数(Function)。
    • 其赋值是一个地址引用。栈内存中存放的是这些类型的指针(指向的是堆内存的地址),而其具体的值是放在堆内存中的。在使用的时候,根据栈内存中的地址,来找到存放在堆内存的值。
    • 使用instanceof检测数据类型。

2、函数传参

  • 参数传入值类型的数据:函数将传入的值复制赋值给对应的参数。
    let one = 1
    let two = 2
    function add(x, y) {
      return x + y;
    }
    const three = add(one, two) // 3
    
  • 参数传入引用类型的数据:函数会将其引用地址赋值给对应的参数,在函数内操作参数会影响到原对象
    function changeAgeImpure(person) {
      person.age = 25; // person 与 alex 的引用是一致的,即指向同一个堆内存
      return person;
    }
    let alex = {
      name: 'Alex',
      age: 30
    };
    let changedAlex = changeAgeImpure(alex);
    console.log(alex); // { name: 'Alex', age: 25 }
    console.log(changedAlex); // { name: 'Alex', age: 25 }
    
    稍微修改修改:
    function changeAgeAndReference(person) {
      person.age = 25;
      person = {            // 会改变 person 的引用
        name: 'John',
        age: 50
      };
    
      return person;
    }
    var personObj1 = {
      name: 'Alex',
      age: 30
    };
    var personObj2 = changeAgeAndReference(personObj1);
    console.log(personObj1); // -> {name: "Alex", age: 25}
    console.log(personObj2); // -> {name: "John", age: 50}