METADATA
title: 《JavaScript高级程序设计 第四章》通过内存空间探究ES中基本类型和引用类型的异同d
ate: 2018-11-04 22:30
tags: [前端,高程学习笔记]
categories: 技术
在开发过程中我们对基本类型和引用类型的一些特性有所了解:
基本类型是按值访问的,所以我们可以尽情地赋值修改不用担心有副作用;
而引用类型是按引用访问的,所以这会导致当我们操作一个复制自另一个引用类型的值时,使得另一个值也发生变化。
说起来可能有点拗口,又是复制又是赋值的,还有什么按值访问按引用访问,看一下demo:
// 声明两个基本类型的变量,simpleVariable2复制自simpleVariable1
let simpleVariable1 = 'simpleVariable1';
let simpleVariable2 = simpleVariable1;
// 打印出两个变量的值,没有什么问题
console.log(simpleVariable1); // simpleVariable1
console.log(simpleVariable2); // simpleVariable1
// 修改 simpleVariable2 的值,一切如预期
simpleVariable2 = 'simpleVariable2';
console.log(simpleVariable1); // simpleVariable1
console.log(simpleVariable2); // simpleVariable2
// 声明两个复杂类型的变量,complexVariable2复制自complexVariable1
let complexVariable1 = {
name: 'complexVariable1',
};
let complexVariable2 = complexVariable1;
// 打印出两个变量的值,没有什么问题
console.log(complexVariable1); // name:complexVariable1
console.log(complexVariable2); // name:complexVariable1
// 修改complexVariable2中的值,一切就不如预期了:complexVariable1中的值也发生了变化
complexVariable2.name = 'complexVariable2';
console.log(complexVariable1); // name:complexVariable2
console.log(complexVariable2); // name:complexVariable2
本文基于以上代码反映的问题对基本类型和引用类型从内存空间的角度做深入学习,从而对变量的声明、引用过程有更深的理解,间接达到提升代码质量的作用。
《JavaScript高级程序设计》中包含的这些内容的章节:4.1 基本类型和引用类型的值
参考文章:
Does JavaScript use stack or heap for memory allocation or both?