Understand JavaScript encapsulation
Encapsulation can be defined as hiding the internal data representation and implementation details of an object. Information hiding can be enforced through encapsulation.
In JavaScript, there are no explicit keywords for declaring private members. Therefore, if you want to achieve encapsulation/information hiding, you need to start from another idea. We can use the concept of closures to create methods and properties that are only accessible from within the object to achieve encapsulation requirements.
Basic methods
Generally speaking, we learn to use three methods to achieve the purpose of encapsulation.
Use this.XXX to declare a variable, and then declare getXXX, setXXX and other value acquisition and assignment methods.
Use this._XXX to declare a variable, and then declare getXXX, setXXX and other value acquisition and assignment methods.
Use the concept of "function scope" to do this.
1. Open portal
var Book = function(isbn,title,author){ this.setIsbn(isbn); this.setTitle(title); this.setAuthor(author); }; Book.prototype = { setIsbn: function(isbn){ this.isbn = isbn; }, getIsbn: function(){ return this.isbn; }, setTitle: function(title){ this.title = title; }, getTitle: function(){ return this.title; }, setAuthor: function(author){ this.author = author; }, getAuthor: function(){ return this.author; } };
Use this method to achieve Encapsulation, although valuers and assigners are implemented to protect private properties. But in actual use, private properties can still be accessed from the outside, so fundamentally, encapsulation is not implemented.
2. Use naming conventions to differentiate
var Book = function(isbn,title,author){ this.setIsbn(isbn); this.setTitle(title); this.setAuthor(author); }; Book.prototype = { setIsbn: function(isbn){ this._isbn = isbn; }, getIsbn: function(){ return this._isbn; }, setTitle: function(title){ this._title = title; }, getTitle: function(){ return this._title; }, setAuthor: function(author){ this._author = author; }, getAuthor: function(){ return this._author; } };
Use this method with the first Similar, except that different naming is used to protect the use of private properties. However, from a practical application perspective, it still does not implement encapsulation.
3. Using function scope
var Book = function(newIsbn,newTitle,newAuthor){ var isbn,title,author; this.setIsbn=function(newIsbn){ isbn = newIsbn; }; this.getIsbn=function(){ return isbn; }; this.setTitle=function(newTitle){ title = newTitle; }; this.getTitle=function(){ return title; }; this.setIsbn=function(newAuthor){ author = newAuthor; }; this.getIsbn=function(){ return author; }; }
is declared in a JavaScript function Variables are scoped, so using this method avoids direct access to private properties from outside. Basically achieve the content required for packaging.
What should be noted here is that we can use this.XXX and var to declare variables inside the function. The difference is that variables declared using this.XXX are accessible externally. Variables declared using var are protected by the function scope and cannot be directly accessed outside the function.
4. Use the transformation of function scope
var Book = (function(){ // ...其他静态方法 return function(newIsbn,newTitle,newAuthor){ var isbn,title,author; this.setIsbn=function(newIsbn){ isbn = newIsbn; }; this.getIsbn=function(){ return isbn; }; this.setTitle=function(newTitle){ title = newTitle; }; this.getTitle=function(){ return title; }; this.setIsbn=function(newAuthor){ author = newAuthor; }; this.getIsbn=function(){ return author; }; }; })();
This method returns directly Execution of a constructor. And the constructor here is an inline function.
The advantage of this method is that "there will only be one copy in the memory. Because other static methods are declared outside the constructor, they are not privileged methods."
Judge a method The principle of whether it should be designed as a static method is "whether this method will access private properties." If it's not needed, it would be more efficient to design it as a static method since only one copy of it will be created.
Constant
We can use the "only getter, no assignor" approach to implement constants.
// 1. var Book = function(){ var constants = ["key1": "1","key2": "2","key3": "3"]; this.getConstant = function(key){ return constants[key]; }; }; Book.getConstant("key1"); // 2. var Book = (function(){ var constants = ["key1": "1","key2": "2","key3": "3"]; var con = function(){}; con.getConstant = function(name){ return constants[name]; }; return con; })(); Book.getConstant("key1");
Pros and cons
1. Pros
Encapsulation protects the integrity of internal data;
Encapsulation makes it easier to reconstruct objects;
weakens the coupling between modules and improves the reusability of objects;
Yes Helps avoid namespace conflicts;
...
2. Disadvantages
Private methods are difficult to test;
must be associated with complex Dealing with the scope chain makes error scheduling more difficult;
It is easy to cause excessive encapsulation;
JavaScript does not natively support encapsulation, so there are complexity issues in implementing encapsulation in JavaScript;
The above is The entire content of this article is hoped to be helpful to everyone's study.
【Recommended related tutorials】
1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F
