Home Web Front-end JS Tutorial Basic knowledge about creating constants with JavaScript (graphic tutorial)

Basic knowledge about creating constants with JavaScript (graphic tutorial)

May 19, 2018 am 09:09 AM
javascrip basic knowledge constant

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])
 }
 })
}
Copy after login

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')
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are constants in C language? Can you give an example? What are constants in C language? Can you give an example? Aug 28, 2023 pm 10:45 PM

A constant is also called a variable and once defined, its value does not change during the execution of the program. Therefore, we can declare a variable as a constant referencing a fixed value. It is also called text. Constants must be defined using the Const keyword. Syntax The syntax of constants used in C programming language is as follows - consttypeVariableName; (or) consttype*VariableName; Different types of constants The different types of constants used in C programming language are as follows: Integer constants - For example: 1,0,34, 4567 Floating point constants - Example: 0.0, 156.89, 23.456 Octal and Hexadecimal constants - Example: Hex: 0x2a, 0xaa.. Octal

How to create a constant in Python? How to create a constant in Python? Aug 29, 2023 pm 05:17 PM

Constants and variables are used to store data values ​​in programming. A variable usually refers to a value that can change over time. A constant is a type of variable whose value cannot be changed during program execution. There are only six built-in constants available in Python, they are False, True, None, NotImplemented, Ellipsis(...) and __debug__. Apart from these constants, Python does not have any built-in data types to store constant values. Example An example of a constant is demonstrated below - False=100 outputs SyntaxError:cannotassigntoFalseFalse is a built-in constant in Python that is used to store boolean values

In Java, is it possible to define a constant using only the final keyword? In Java, is it possible to define a constant using only the final keyword? Sep 20, 2023 pm 04:17 PM

A constant variable is a variable whose value is fixed and only one copy exists in the program. Once you declare a constant variable and assign a value to it, you cannot change its value again throughout the program. Unlike other languages, Java does not directly support constants. However, you can still create a constant by declaring a variable static and final. Static - Once you declare a static variable, they will be loaded into memory at compile time, i.e. only one copy will be available. Final - Once you declare a final variable, its value cannot be modified. Therefore, you can create a constant in Java by declaring the instance variable as static and final. Example Demonstration classData{&am

PHP error: How to solve the problem when calling undefined constant? PHP error: How to solve the problem when calling undefined constant? Aug 26, 2023 pm 03:39 PM

PHP is a server-side scripting language widely used in web development. Its flexibility and ease of use make it the first choice for many developers. However, when using PHP, we sometimes encounter some error reports. This article will focus on the "Call to undefined constant" error and how to resolve it. 1. Problem Description When we use an undefined constant in the code, PHP will throw a fatal error, prompting us to call an undefined constant. Here is a common example: echoMY_

A must-read for learning MySQL! Detailed explanation of the basic knowledge of SQL statements A must-read for learning MySQL! Detailed explanation of the basic knowledge of SQL statements Jun 15, 2023 pm 09:00 PM

MySQL is an open source relational database management system that is widely used in web application development and data storage. Learning MySQL's SQL language is very necessary for data managers and developers. SQL language is the core part of MySQL, so before learning MySQL, you need to have a full understanding of SQL language. This article aims to explain the basic knowledge of SQL statements to you in detail, so that you can understand SQL statements step by step. SQL is the abbreviation of Structured Query Language, which is used in relational data

Definition and initialization methods of basic data type constants study guide Definition and initialization methods of basic data type constants study guide Jan 05, 2024 pm 02:08 PM

To learn the definition and initialization method of basic data type constants, specific code examples are required. In programming, various basic data types are often used, such as integers, floating point types, character types, etc. When using these data types, you not only need to understand their definition and usage, but also how to define and initialize their constants. This article will introduce you to the definition and initialization method of basic data type constants, and give specific code examples. Definition and initialization method of integer constants Integer constants include int, long, short and byt

Some basic knowledge of Yii framework Some basic knowledge of Yii framework Jun 21, 2023 pm 07:07 PM

Yii is a popular object-oriented PHP framework. Its full name is "YesItIs", which means "Yes, it is like this". It is designed to be efficient, fast, secure and easy to use, so it is widely used in the development of large-scale web applications. In this article, we will introduce some basic knowledge of Yii framework to help novices better understand this framework. MVC architecture Yii framework adopts a design pattern based on MVC (Model-View-Controller), which

What basic concepts do you need to understand to learn canvas? What basic concepts do you need to understand to learn canvas? Jan 17, 2024 am 10:37 AM

What basic knowledge do you need to learn canvas? With the development of modern web technology, using the <canvas> tag in HTML5 for drawing has become a common way. Canvas is an HTML element used to draw graphics, animations and other images, which can be manipulated and controlled using JavaScript. If you want to learn canvas and master its basic knowledge, the following will introduce it to you in detail. HTML and CSS basics: before learning canvas

See all articles