An easy introduction to object-oriented JavaScript
This chapter assumes that everyone has read the author's previous article "JavaScriptEasy Introduction to Object-OrientedAbstraction"
Why encapsulation?
Encapsulation is to hide the internal properties and methods of an object. External code can only access the object through a specific interface. This is also part of the idea of interface-oriented programming.
Encapsulation is a very important part of object-oriented programming. Let’s take a look at what the code without encapsulation looks like:
1 function Dog(){2 this.hairColor = '白色';//string3 this.breed = '贵宾';//string4 this.age = 2;//number5 }6 var dog = new Dog();7 console.log(dog.breed);//log: '贵宾'
There seems to be no problem, but what if the breed attribute name is changed? For example, if this.type = ‘VIP’, , then all codes using the Dog class must be changed.
If you write the code for the class and the code for using the class, and there are not many places to use this class, it doesn’t matter if you write it this way.
But if this class is used in many places, or other people also use your class during collaborative development, then doing so will make the code difficult to maintain. The correct approach is:
1 function Dog(){ 2 this.hairColor = '白色';//string 3 this.age = 2;//number 4 this._breed = '贵宾';//string 5 } 6 Dog.prototype.getBreed = function(){ 7 return this._breed; 8 } 9 Dog.prototype.setBreed = function(val){10 this._breed = val;11 }12 var dog = new Dog();13 console.log(dog.getBreed());//log: '贵宾'14 dog.setBreed('土狗');
getBreed() is the interface. If the internal properties change, for example, breed is replaced by type , then you only need to change the code in getBreed(), and you can monitor all operations to obtain this attribute.
Therefore, encapsulation has many benefits:
1. As long as the interface does not change, the internal implementation can be changed arbitrarily; 2. It is very convenient for users to use. It doesn’t matter how it is implemented internally;
3. Reduce the coupling between codes;
4. Meet the collaborative development of large applications and multiple people;
Use getter/setter to encapsulate private properties
Actually there is another way to encapsulate properties, that is Usegetter/setter, as followsdemo, this chapter does not talk about the principles, only the use. You can check the information yourself for the principles:
1 function Dog(){ 2 this.hairColor = '白色';//string 3 this.age = 2;//number 4 this._breed = '贵宾';//string 5 Object.defineProperty(this, 'breed', {//传入this和属性名 6 get : function () { 7 console.log('监听到了有人调用这个get breed') 8 return this._breed; 9 },10 set : function (val) {11 this._breed = val;12 /*13 如果不设置setter的话默认这个属性是不可设置的14 但有点让人诟病的是,浏览器并不会报错15 所以即使你想让breed是只读的,你也应该设置一个setter让其抛出错误:16 throw 'attribute "breed" is read only!';17 */18 }19 });20 }21 var dog = new Dog();22 console.log(dog.breed);23 /*log:24 '监听到了有人调用这个get breed接口'25 '贵宾'26 */27 dog.breed = '土狗';28 console.log(dog.breed);29 /*log:30 '监听到了有人调用这个get breed接口'31 '土狗'32 */
getBreed(), getter/setterGenerally used in readonly attributes and some more important interfaces, as well as reconstructing attribute operations that do not encapsulate interfaces. You can also use closures to encapsulate private properties, which is the safest, but will cause additional memory overhead, so the author doesn't like to use it very much. You can learn about it yourself.
Public/Private concept In the first two sections, we briefly understood encapsulation, but these are definitely not enough Used, let's first understand the following concepts:
Private properties: Properties that can only be accessed and modified within the class, and external access is not allowed.
Private method: A method that can only be called internally within the class, and is prohibited from being called externally.
Public attributes: Attributes that can be obtained and modified outside the class. Theoretically, all attributes of a class should be private attributes and can only be accessed through encapsulated interfaces. However, for some smaller classes or classes that are used less frequently, you do not need to encapsulate the interface if you find it more convenient.
Public methods: Methods that can be called externally. Methods that implement interfaces such as getBreed() are public methods, as well as behavioral methods exposed to the outside world.
Static properties, static methods: The properties and methods of the class itself. There is no need to distinguish between public and private. All static properties and static methods must be private and must be accessed through the encapsulated interface. This is why the author in the previous chapter used getInstanceNumber() to access Dog.instanceNumberProperty.
ES5 demo is as follows:
1 function Dog(){ 2 /*公有属性*/ 3 this.hairColor = null;//string 4 this.age = null;//number 5 /*私有属性,人们共同约定私有属性、私有方法前面加上_以便区分*/ 6 this._breed = null;//string 7 this._init(); 8 /*属性的初始化最好放一个私有方法里,构造函数最好只用来声明类的属性和调用方法*/ 9 Dog.instanceNumber++;10 }11 /*静态属性*/12 Dog.instanceNumber = 0;13 /*私有方法,只能类的内部调用*/14 Dog.prototype._init = function(){15 this.hairColor = '白色';16 this.age = 2;17 this._breed = '贵宾';18 }19 /*公有方法:获取属性的接口方法*/20 Dog.prototype.getBreed = function(){21 console.log('监听到了有人调用这个getBreed()接口')22 return this._breed;23 }24 /*公有方法:设置属性的接口方法*/25 Dog.prototype.setBreed = function(breed){26 this._breed = breed;27 return this;28 /*这是一个小技巧,可以链式调用方法,只要公有方法没有返回值都建议返回this*/29 }30 /*公有方法:对外暴露的行为方法*/31 Dog.prototype.gnawBone = function() {32 console.log('这是本狗最幸福的时候');33 return this;34 }35 /*公有方法:对外暴露的静态属性获取方法*/36 Dog.prototype.getInstanceNumber = function() {37 return Dog.instanceNumber;//也可以this.constructor.instanceNumber38 }39 var dog = new Dog();40 console.log(dog.getBreed());41 /*log:42 '监听到了有人调用这个getBreed()接口'43 '贵宾'44 */45 /*链式调用,由于getBreed()不是返回this,所以getBreed()后面就不可以链式调用了*/46 var dogBreed = dog.setBreed('土狗').gnawBone().getBreed();47 /*log:48 '这是本狗最幸福的时候'49 '监听到了有人调用这个getBreed()接口'50 */51 console.log(dogBreed);//log: '土狗'52 console.log(dog);
ES6 demo
(Novices don’t want to watch this ES6 and TypeScrpt implementation part):
1 class Dog{ 2 constructor(){ 3 this.hairColor = null;//string 4 this.age = null;//number 5 this._breed = null;//string 6 this._init(); 7 Dog.instanceNumber++; 8 } 9 _init(){10 this.hairColor = '白色';11 this.age = 2;12 this._breed = '贵宾';13 }14 get breed(){15 /*其实就是通过getter实现的,只是ES6写起来更简洁*/16 console.log('监听到了有人调用这个get breed接口');17 return this._breed;18 }19 set breed(breed){20 /*跟ES5一样,如果不设置的话默认breed无法被修改,而且不会报错*/21 console.log('监听到了有人调用这个set breed接口');22 this._breed = breed;23 return this;24 }25 gnawBone() {26 console.log('这是本狗最幸福的时候');27 return this;28 }29 getInstanceNumber() {30 return Dog.instanceNumber;31 }32 }33 Dog.instanceNumber = 0;34 var dog = new Dog();35 console.log(dog.breed);36 /*log:37 '监听到了有人调用这个get breed接口'38 '贵宾'39 */40 dog.breed = '土狗';//log:'监听到了有人调用这个set breed接口'41 console.log(dog.breed);42 /*log:43 '监听到了有人调用这个get breed接口'44 '土狗'45 */
ES5、ES6中虽然我们把私有属性和方法用“_”放在名字前面以区分,但外部还是可以访问到属性和方法的。
TypeScrpt中就比较规范了,可以声明私有属性,私有方法,并且外部是无法访问私有属性、私有方法的:
1 class Dog{ 2 public hairColor: string; 3 readonly age: number;//可声明只读属性 4 private _breed: string;//虽然声明了private,但还是建议属性名加_以区分 5 static instanceNumber: number = 0;//静态属性 6 constructor(){ 7 this._init(); 8 Dog.instanceNumber++; 9 }10 private _init(){11 this.hairColor = '白色';12 this.age = 2;13 this._breed = '贵宾';14 }15 get breed(){16 console.log('监听到了有人调用这个get breed接口');17 return this._breed;18 }19 set breed(breed){20 console.log('监听到了有人调用这个set breed接口');21 this._breed = breed;22 }23 public gnawBone() {24 console.log('这是本狗最幸福的时候');25 return this;26 }27 public getInstanceNumber() {28 return Dog.instanceNumber;29 }30 }31 let dog = new Dog();32 console.log(dog.breed);33 /*log:34 '监听到了有人调用这个get breed接口'35 '贵宾'36 */37 dog.breed = '土狗';//log:'监听到了有人调用这个set breed接口'38 console.log(dog.breed);39 /*log:40 '监听到了有人调用这个get breed接口'41 '土狗'42 */43 console.log(dog._breed);//报错,无法通过编译44 dog._init();//报错,无法通过编译
注意事项:
1、暴露给别人的类,多个类组合成一个类时,所有属性一定都要封装起来;
2、如果你来不及封装属性,可以后期用getter/setter弥补;
3、每个公有方法,最好注释一下含义;
4、在重要的类前面最好用注释描述所有的公有方法;
后话
如果你喜欢作者的文章,记得收藏,你的点赞是对作者最大的鼓励;
作者会尽量每周更新一章,下一章是讲继承;
大家有什么疑问可以留言或私信作者,作者尽量第一时间回复大家;
如果老司机们觉得那里可以有不恰当的,或可以表达的更好的,欢迎指出来,我会尽快修正、完善。
The above is the detailed content of An easy introduction to object-oriented JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use