博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] Understand common misconceptions about ES6's const keyword
阅读量:7240 次
发布时间:2019-06-29

本文共 1070 字,大约阅读时间需要 3 分钟。

Values assigned with let and const are seen everywhere in JavaScript. It's become common to hear them explained like so:

"const creates an constant (immutable) binding while bindings created with let can be changed (mutated) without issue."

Although this is an accurate description, it's often misinterpreted to mean that data bound with let is mutable, while data bound via const is immutable, however this doesn't happen to be the case. In this lesson we'll explore this topic further and learn how to create immutable objects in the form of shallow copies using .

 

It is possible to update array's item value:

const magicNumbers = [1,2,3];magicNumbers[0] = 4;console.log(magicNumbers) // 4,2,3

But not able to reassign:

const magicNumbers = [1,2,3];magicNumbers = [4,5,6]; // error

 

We can create immutable object in form of shallow copies using Object.freeze:

const magicNumbers = Object.freeze([1,2,3]);magicNumbers[0] = 4; // cannot update the value, but no error

 

If we want error report:

"use strict";const magicNumbers = Object.freeze([1,2,3]);magicNumbers[0] = 4;

 

转载地址:http://bgybm.baihongyu.com/

你可能感兴趣的文章
Go语言获取命令行参数
查看>>
C#操作Office实例
查看>>
线程,进程 ,队列 基本用法总结
查看>>
每周总结
查看>>
分布类的使用
查看>>
单词倒排
查看>>
洛谷 P2709 小B的询问
查看>>
Future模式
查看>>
hibernate 缓存问题
查看>>
5.2 Array类型介绍
查看>>
0阶 无符号指数哥伦布编码
查看>>
初入博客园
查看>>
[NOIP2013] 提高组 洛谷P1967 货车运输
查看>>
E: Unable to correct problems, you have held broken packages-之apt-get 下载报依赖问题
查看>>
递归函数
查看>>
浏览器 UserAgent 相关知识整理
查看>>
18、配置嵌入式servlet容器(2)
查看>>
URL重写
查看>>
移植spdylay到libcurl
查看>>
Codeforces Round #447 (Div. 2) C. Marco and GCD Sequence【构造/GCD】
查看>>