


This article is divided into two parts. The upper part talks about basic patterns: full exposure, underline notation and using closures; the lower part talks about Advanced Patterns, how to implement static methods and properties, constants and other knowledge points. .
Encapsulation is a very basic and useful feature of object-oriented languages. Although JavaScript can also be called an object-oriented language, its support for encapsulation is not very good. Unlike other languages, as long as you use private and protected It can be achieved. But this does not mean that there is no way. Below I will introduce how to implement encapsulation in JavaScript.
1. Basic patterns, mainly includes three methods: full exposure method, underline notation method and using closure. (Closure is a very important and difficult concept. Friends who are interested can find information online. I have also reprinted other people's articles on my blog).
Here we take the book class as an example, and we need to create and initialize the book class.
// Book(isbn, title, author)
var theHobbit = new Book('0-395-07122-4', 'The Hobbit', 'J. R. R. Tolkien');
theHobbit.display(); // Outputs the data by creating and populating an HTML element.
1. Full exposure method:
Creating the book class can use the most traditional constructor method,
var Book = function(isbn, title, author) {
if(!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this.isbn = isbn;
//The function of || in the code is that if title has no value, 'No title specified' will be assigned to this.title. This method is very useful and you can use it in your own code.
this.title = title || 'No title specified';
this.author = author || 'No author specified';
}
Book.prototype = {
//Verification isbn function
checkIsbn: function(isbn) {
},
//Set isbn
setIsbn: function(isbn) {
if(!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this. isbn = isbn;
},
// Get title
getTitle: function() {
return this.title;
},
// Set title
setTitle: function(title) {
this.title = title || 'No title specified';
},
//Get the author
getAuthor: function() {
return this.author;
},
//Set the author
setAuthor: function(author) {
this.author = author || 'No author specified';
},
//Display function
display: function() {
...
}
};
There is a lot of code, I will briefly explain it here. Creating classes in JavaScript is a bit different from C# and Java. C# and Java will wrap all methods and attributes in a class file, for example
Copy code
set
{
this.isbn=value; (string isdn)
{
......
}
......
public void Display()
{
.... .
}
}
Javascript can also use this method, but it is recommended to use the method I used above to define the attributes into the class definition function (or constructor) and the method into the prototype object. This approach has better performance. As for the reason, you can Go to google.
The function that the above js code wants to achieve is to define a book class, which includes three private variables (or attributes) isbn, title, author, a private method checkIsbn, and several public methods getIsdn, setIsdn,. ..display. The idea is good, but the reality is cruel. In fact, those private properties or methods are not private at all. For example, theHobbit.isbn = '978-0261103283'; You can assign a value to isbn in this way without error and absolutely successful. The reason is that JavaScript has no private way to privatize specific objects. In addition, this implementation method can also cause confusion when using it. What properties and methods does the creator of the class want to expose? The first improvement method is introduced below, the underline marking method.
2. Underline notation:
var Book = function(isbn, title, author) {
// Constructor code.
this.setIsbn(isbn);
this.setTitle(title);
this.setAuthor(author);
}
Book.prototype = {
//Verify isbn function
_checkIsbn: function(isbn) {
... function() { return this._isbn;
},
//Set isbn
setIsbn: function(isbn) { ('Book: Invalid ISBN.'); This._isbn = isbn;
},
...
display: function() { . ..
}
};
In fact, just add an underscore _ in front of all properties or methods that you want to implement privately, and there is no other operation. This method does not achieve true privatization. theHobbit._isbn = '978-0261103283'; This operation is still successful. The greatest significance of this method is to tell the users of the class which objects the author intends to expose and which ones he does not want to expose. . But the author has no control over whether users follow the author's ideas.
So is there a way to achieve true privatization? The answer is yes, it is to use closures.
3. Use closures:
The reason why JavaScript can achieve true encapsulation is inseparable from its unique function scope, function support for internal functions, and closures. You can go online to collect relevant knowledge to deepen your understanding.
The first thing I will talk about below is the function scope. In JavaScript, if a variable is defined inside a function, there is no way to access it from outside the function. In fact, implementing private properties or methods in JavaScript takes advantage of this special property. Example:
Copy code
The code is as follows:
in In the above example, function foo defines variable a and method bar internally. A and bar cannot be accessed from outside foo, but because a and bar are both defined inside foo, bar can access a. So is there a way to access bar outside foo? The answer is yes, it is to use a closure.
Copy code
The code is as follows:
var baz = foo(); // baz is now a reference to function bar.
baz(); // returns 20.
baz(); // returns 40.
baz(); // returns 80.
var blat = foo(); // blat is another reference to bar.
blat(); // returns 20, because a new copy of a is being used.
This is what was mentioned earlier JavaScript functions support internal functions. The internal function bar can access the private variable a, and the function foo throws the internal function bar to baz, and baz can access the internal variable a, which implements closure. Everyone will understand at a glance. In this way, private variables and methods are actually implemented. Returning to our previous book example, the implementation is as follows:
Copy the code
The code is as follows:
var Book = function(newIsbn, newTitle, newAuthor) {
// implements Publication
// Private attributes.
var isbn, title, author;
// Private method.
function checkIsbn(isbn) {
...
}
// Privileged methods.
this.getIsbn = function() {
return isbn;
};
this.setIsbn = function(newIsbn) {
if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
isbn = newIsbn;
};
this.getTitle = function() {
return title;
};
this.setTitle = function(newTitle) {
title = newTitle || 'No title specified';
};
this.getAuthor = function() {
return author;
};
this.setAuthor = function(newAuthor) {
author = newAuthor || 'No author specified';
};
// Constructor code.
this.setIsbn(newIsbn);
this.setTitle(newTitle);
this.setAuthor(newAuthor);
};
// Public, non-privileged methods.
Book.prototype = {
display: function() {
...
}
};
上述代码就实现了 isbn, title, author和checkIsbn的私有化,外部是决定不能直接访问到的。如需访问 isbn, title, author只能通过对象级的方法getTitle,setTitle...。比如要给isbn赋值,只能用theHobbit.setIsbn = '978-0261103283';,如果你还用theHobbit._isbn = '978-0261103283';,对不起要报错了。
好了,今天的内容就讲到这里了,希望对大家有帮助。
作者:下一站永远

本站4月17日消息,集邦咨询(TrendForce)近日发布报告,认为英伟达Blackwell新平台产品需求看涨,预估带动台积电2024年CoWoS封装总产能提升逾150%。英伟达Blackwell新平台产品包括B系列的GPU,以及整合英伟达自家GraceArmCPU的GB200加速卡等。集邦咨询确认为供应链当前非常看好GB200,预估2025年出货量有望超过百万片,在英伟达高端GPU中的占比达到40-50%。在英伟达计划下半年交付GB200以及B100等产品,但上游晶圆封装方面须进一步采用更复

本站7月9日消息,AMDZen5架构“Strix”系列处理器会有两种封装方案,其中较小的StrixPoint将采用FP8封装,而StrixHalo将会采用FP11封装。图源:videocardz消息源@Olrak29_最新曝料称StrixHalo的FP11封装尺寸为37.5mm*45mm(1687平方毫米),和英特尔AlderLake、RaptorLakeCPU的LGA-1700封装尺寸相同。AMD最新的PhoenixAPU采用FP8封装方案,尺寸为25*40mm,这意味着StrixHalo的F

Vue中Axios封装及其常用方法介绍Axios是一款基于Promise实现的HTTP库,它的优点在于具有良好的可读性、易用性以及可扩展性。Vue作为一款流行的前端框架,也对Axios提供了全面支持。本文将介绍如何在Vue中进行Axios封装,并且介绍Axios常用的一些方法。一、Axios封装在开发过程中,我们常常需要对Axios进行一些自定义的封装,例如

PHP中的封装技术及应用封装是面向对象编程中的一个重要概念,它指的是将数据和对数据的操作封装在一起,以便提供对外部程序的统一访问接口。在PHP中,封装可以通过访问控制修饰符和类的定义来实现。本文将介绍PHP中的封装技术及其应用场景,并提供一些具体的代码示例。一、封装的访问控制修饰符在PHP中,封装主要通过访问控制修饰符来实现。PHP提供了三个访问控制修饰符,

通过封装代码,C++函数可以提高GUI开发效率:代码封装:函数将代码分组到独立单元,使代码易于理解和维护。可重用性:函数可创建通用功能供应用程序中重复使用,减少重复编写和错误。简洁代码:封装代码使主逻辑简洁,便于阅读和调试。

如何在Go语言中实现封装和继承封装和继承是面向对象编程中的两个重要概念,它们可以使代码更加模块化和可维护,同时也为代码的复用提供了便利。本文将介绍在Go语言中如何实现封装和继承,并提供相应的代码示例。封装封装是将数据和功能进行封装,隐藏实现的细节,只暴露必要的接口给外部使用。在Go语言中,封装是通过导出和非导出标识符来实现的。首字母大写的标识符可以被其他包访

PHP代码封装技巧:如何使用类和对象封装可重复使用的代码块摘要:在开发中,经常遇到需要重复使用的代码块。为了提高代码的可维护性和可重用性,我们可以使用类和对象的封装技巧来对这些代码块进行封装。本文将介绍如何使用类和对象封装可重复使用的代码块,并提供几个具体的代码示例。使用类和对象的封装优势使用类和对象的封装有以下几个优势:1.1提高代码的可维护性通过将重复

本站7月11日消息,经济日报今天(7月11日)报道,富士康集团已进军先进封装领域,重点布局时下主流的面板级扇出封装(FOPLP)半导体方案。1.继旗下群创光电(Innolux)之后,富士康集团投资的夏普(Sharp)也宣布进军日本面板级扇出式封装领域,预计将于2026年投产。富士康集团在AI领域本身就有足够的影响力,而补上先进封装短板之后让其可以提供“一条龙”服务,便于后续接受更多的AI产品订单。本站查询公开资料,富士康集团目前持有夏普10.5%的股权,该集团表示现阶段不会增持,也不会减持,将维


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
