Table of Contents
Why encapsulation?
注意事项:
后话
Home Web Front-end JS Tutorial An easy introduction to object-oriented JavaScript

An easy introduction to object-oriented JavaScript

Jun 26, 2017 am 11:52 AM
javascript js getting Started object easy For

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: '贵宾'
Copy after login

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('土狗');
Copy after login

 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 Use

getter/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     */
Copy after login

But this method is more cumbersome to write. The author usually uses

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

 

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     */
Copy after login

 

  ES5ES6中虽然我们把私有属性和方法用“_”放在名字前面以区分,但外部还是可以访问到属性和方法的。

  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();//报错,无法通过编译
Copy after login

 

注意事项:

  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!

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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

A Diffusion Model Tutorial Worth Your Time, from Purdue University A Diffusion Model Tutorial Worth Your Time, from Purdue University Apr 07, 2024 am 09:01 AM

Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Aug 01, 2024 pm 03:28 PM

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award Jun 20, 2024 pm 05:43 PM

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts Jul 24, 2024 pm 08:13 PM

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

A must-read for technical beginners: Analysis of the difficulty levels of C language and Python A must-read for technical beginners: Analysis of the difficulty levels of C language and Python Mar 22, 2024 am 10:21 AM

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days Aug 07, 2024 pm 10:53 PM

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Jul 11, 2024 pm 01:53 PM

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution

See all articles