search
HomeWeb Front-endJS TutorialBasic knowledge about creating constants with JavaScript (graphic tutorial)
Basic knowledge about creating constants with JavaScript (graphic tutorial)May 19, 2018 am 09:09 AM
javascripbasic knowledgeconstant

This article mainly introduces the relevant knowledge points about creating constants in JavaScript to help you learn more about JS. Please refer to it.

This article conducts an in-depth analysis of the definition and usage of constants in JS and common errors in function writing. I hope it will be useful to everyone:

The so-called constants can only be read but not edited (delete , modified) variables.

js does not have the original constant statement (that is, customized, original), but it can be created in some remote ways.

1: const declaration keyword in es6.

#The two variables are declared above, and an error will be reported when the modification operation is performed. To some extent, const can create variables (basic types). But reference types are hard to come by.

#When the declared variable is a reference type, it is an object, and operations on the object (deletion, modification, addition) can be performed.

2: Object method (defineProperty, seal, freeze) implementation

1) Object.defineProperty: This method will directly define a new property on an object, or modify the existing property of an object properties, and returns this object.​

#After using the above method, the subsequent modification function of a will be invalid. Although the modification function cannot be executed normally, the deletion function can still be performed as usual.

When you continue to add the a attribute after deletion, a becomes changeable again. The above just changes the writable attribute of the a attribute, and there is also a configurable attribute that can be set. The writable attribute only changes the corresponding attribute so that it cannot be changed directly, but it can be done in a small way (delete first and then add).

# Even if attribute a is finalized, it cannot be modified or deleted.

However, a new storm has emerged. . . Although a has been decided, it is not over yet for the variable TEST_D. . .

Although attribute a cannot be changed, it does not affect the operation of other attributes, such as b, s, u. Of course, these attributes can also be used as above. The descriptors of other attributes are also used, but the extension to TEST_D still cannot be solved.

2) Object.preventExtensions: This method makes an object non-extensible, that is, new properties can never be added. View details

# Through this method, the object can be set to be non-expandable, that is, new attributes cannot be added, so this variable cannot be modified.

3) Object.seal: Let an object be sealed and return the sealed object. The new object will become non-extensible, that is, new properties cannot be added but properties that were originally writable can be modified

It is possible to create constants by using the above two methods in a loop, but it is more complicated, and when the object is relatively large, the amount of code will be relatively large. Object.seal() can simplify this process. This method can make the object non-extensible and the properties cannot be deleted. On this basis, by changing the descriptors of all properties of the object from writable to false, we can get the variables we want, which are so-called constants.

4) Object.freeze: This method can freeze an object. Freezing means that new attributes cannot be added to the object, the values ​​of existing attributes cannot be modified, existing attributes cannot be deleted, and cannot be modified. The object has enumerability, configurability, and writability properties. In other words, this object is always immutable. This method returns the frozen object.

The Object.freeze method is based on seal and changes the descriptor writable of all properties to false.

But when the attribute value of the variable is an object, and the following situations:

For the user attribute , its value can still be changed, and it must be frozen at this time.

/**
 * 
 * 
 * @param {any} obj 
 */
function freezeObj(obj) {
 Object.freeze(obj);
 Object.keys(obj).forEach(key => {
 if (typeof obj[key] === 'object') {
  freezeObj(obj[key])
 }
 })
}

That is: when there are multiple objects, the freezing method needs to be called cyclically.

3: Closure

const USER = (() => {
 const USER = {
 name: 'evening',
 gender: 'M'
 }
 return {
 get(name){
  return user[name]
 }
 }
})()
USER.get('name')

The closure uses a relatively secret method to save the real object prototype in the memory and will not be recycled, thus 'protecting' the USER variable in disguise up, and provides an access interface, but does not provide an interface for modification.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Vue.jsDetailed explanation of calculation and use of listener properties

jsSummary of the advantages and disadvantages of the three calling methods

Dynamic introductionjsSummary of the four methods

The above is the detailed content of Basic knowledge about creating constants with JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C语言中的常量是什么,可以举一个例子吗?C语言中的常量是什么,可以举一个例子吗?Aug 28, 2023 pm 10:45 PM

常量也称为变量,一旦定义,其值在程序执行期间就不会改变。因此,我们可以将变量声明为引用固定值的常量。它也被称为文字。必须使用Const关键字来定义常量。语法C编程语言中使用的常量语法如下-consttypeVariableName;(or)consttype*VariableName;不同类型的常量在C编程语言中使用的不同类型的常量如下所示:整数常量-例如:1,0,34,4567浮点数常量-例如:0.0,156.89,23.456八进制和十六进制常量-例如:十六进制:0x2a,0xaa..八进制

如何在Python中创建一个常量?如何在Python中创建一个常量?Aug 29, 2023 pm 05:17 PM

常量和变量用于在编程中存储数据值。变量通常指的是可以随时间变化的值。而常量是一种变量类型,其值在程序执行期间不能被改变。在Python中只有六个内置常量可用,它们是False、True、None、NotImplemented、Ellipsis(...)和__debug__。除了这些常量之外,Python没有任何内置数据类型来存储常量值。示例下面演示了常量的示例-False=100输出SyntaxError:cannotassigntoFalseFalse是Python中的内置常量,用于存储布尔值

在Java中,仅使用final关键字可以定义一个常量吗?在Java中,仅使用final关键字可以定义一个常量吗?Sep 20, 2023 pm 04:17 PM

常量变量是其值固定且程序中只存在一个副本的变量。一旦你声明了一个常量变量并给它赋值,你就不能在整个程序中再次改变它的值。与其他语言不同,Java不直接支持常量。但是,你仍然可以通过声明一个变量为静态和final来创建一个常量。静态-一旦你声明了一个静态变量,它们将在编译时加载到内存中,即只有一个副本可用。Final-一旦你声明了一个final变量,就不能再修改它的值。因此,你可以通过将实例变量声明为静态和final来在Java中创建一个常量。示例 演示classData{&am

PHP报错:调用未定义的常量怎么解决?PHP报错:调用未定义的常量怎么解决?Aug 26, 2023 pm 03:39 PM

PHP是一种广泛应用于网页开发的服务器端脚本语言,它的灵活性和易用性使其成为许多开发人员的首选。然而,在使用PHP时,我们有时会遇到一些报错的情况。本篇文章将重点讨论"调用未定义的常量"错误,以及如何解决这个问题。一、问题描述当我们在代码中使用一个未定义的常量时,PHP会抛出一个致命错误,提示我们调用了一个未定义的常量。下面是一个常见的例子:echoMY_

PHP报错:使用未定义的常量作为属性名怎么办?PHP报错:使用未定义的常量作为属性名怎么办?Aug 17, 2023 pm 02:13 PM

PHP报错:使用未定义的常量作为属性名怎么办?在PHP开发中,我们经常会使用类和对象来组织和管理代码。在定义一个类的过程中,类的属性(即成员变量)起到了保存数据的重要作用。然而,当我们在使用属性时,有时会发生使用未定义的常量作为属性名的错误。本文将介绍这种错误的原因,并且提供几种解决方法。首先,让我们看一个简单的例子来演示这个问题。假设我们有一个名为"Per

从头学习:掌握Go语言的基础知识从头学习:掌握Go语言的基础知识Feb 01, 2024 am 08:45 AM

从零开始:学习Go语言的基础知识简介Go语言,又称Golang,是一种由Google开发的开源编程语言。它于2009年发布,并迅速成为一种流行的语言,尤其是在Web开发、分布式系统和云计算等领域。Go语言以其简洁、高效、并发性强等特点而著称。基本语法1.变量和常量在Go语言中,变量和常量都是类型化的。变量可以存储数据,而常量则不能改变。变量的声明格式为:v

学习MySQL必看!详细讲解SQL语句基础知识学习MySQL必看!详细讲解SQL语句基础知识Jun 15, 2023 pm 09:00 PM

MySQL是一个开源的关系型数据库管理系统,被广泛地应用于Web应用程序的开发和数据存储。学习MySQL的SQL语言对于数据管理员和开发者来说是非常必要的。SQL语言是MySQL中的核心部分,因此在学习MySQL之前,你需要对SQL语言有充分的了解,本文旨在为你详细讲解SQL语句基础知识,让你一步步了解SQL语句。SQL是结构化查询语言的简称,用于在关系型数

基本数据类型常量的定义和初始化方法学习指南基本数据类型常量的定义和初始化方法学习指南Jan 05, 2024 pm 02:08 PM

学习基本数据类型常量的定义和初始化方法,需要具体代码示例在编程中,常常会用到各种基本数据类型,比如整型、浮点型、字符型等。在使用这些数据类型时,不仅需要了解它们的定义和用法,还需要知道如何定义和初始化它们的常量。本文将为大家介绍基本数据类型常量的定义和初始化方法,并给出具体的代码示例。整型常量的定义和初始化方法整型常量包括int、long、short和byt

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft