search
HomeWeb Front-endJS TutorialIntroduction to the three basic characteristics of object-oriented JavaScript

Introduction to the three basic characteristics of object-oriented JavaScript

Students who have learned about object-oriented should all know that the three basic characteristics of object-oriented are: encapsulation, inheritance, and polymorphism, but they may not know much about these three words. For the front-end, the most exposed ones may be encapsulation and inheritance, but polymorphism may not be so understood.

Encapsulation

Before talking about encapsulation, let’s first understand what encapsulation is?

What is encapsulation

Encapsulation: Encapsulate the resources required for the object to run in the program object - basic Above, are methods and data. An object "exposes its interface". Other objects attached to these interfaces can use this object without caring about the methods implemented by the object. The concept is "don't tell me how you do it, just do it." An object can be thought of as a self-contained atom. The object interface includes public methods and initialization data. (Excerpted from Baidu Encyclopedia)

My understanding of encapsulation, there may be another step which is Extraction. First of all, you must know which attribute methods you should abstract from in a pair of code. With these as the basis, we can better package.

Encapsulation is nothing more than encapsulation of its properties and methods.

  1. Class: encapsulates the properties and behavior of the object

  2. Method: encapsulates specific logical functions

  3. Access encapsulation: Access modification encapsulation is nothing more than encapsulating its access rights

class Employees {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    getInfo(){
        let {name,age} = this;
        return {name,age};
    }
    static seyHi(){
        console.log("Hi");   
    }
}

let lisi = new Employees("Aaron",18);
lisi.seyHi();   // lisi.seyHi is not a function
lisi.getInfo();  // {name: "Aaron", age: 18}
Employees.seyHi();  // Hi

The public attributes extracted from Employees are name,age, the public methods are getInfo, seyHi, but the difference between getInfo and seyHi is seyHi The static modifier is used to change it to a static method. seyHi only belongs to the Employees class. However, the getInfo method belongs to the instance.

static is used here to encapsulate the access rights of the seyHi method.

Give another example.

Promise.then()  //  Promise.then is not a function
let p1 = new Promise(() => {})
p1.then();  //  Promise {<pending>}
Promise.all([1]);   //  Promise {<resolved>: Array(1)}

As can be seen from the above code, Promise also uses static to encapsulate the access permissions of its methods.

Inheritance

Inheritance: Speaking of inheritance is not unfamiliar. Inheritance can make the subclass have various public properties of the parent classAttributes and public methods. Without having to write the same code again. While letting the subcategory inherit the parent category, you can redefine some attributes and override some methods, that is, overwrite the original attributes and methods of the parent category so that it can obtain different functions from the parent category. (Excerpt from Baidu Encyclopedia)

After a subclass inherits the parent class, the subclass has the properties and methods of the parent class, but it also has its own unique properties and methods. In other words, the functions of the subclass must be More or the same than the parent class, not less than the parent class.

class Employees {
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name)
    }
    static seyHi(){
        console.log("Hi");   
    }
}
class Java extends Employees{
    constructor(name){
        super(name);
    }
    work(){
        console.log("做后台工作");
    }
}
let java = new Java("Aaron");
java.getName();
java.work();
// java.seyHi();    //  java.seyHi is not a function

It can be seen from the above example that inheritance will not inherit the static methods of the parent class, but only the public properties and methods of the parent class. This needs attention.

After inheritance, the subclass not only has the getName method, but also has its own worker method.

Polymorphism

Polymorphism: The literal meaning is "multiple states", allowing the pointer of the subclass type to be assigned to the parent Pointer to class type. (Excerpted from Baidu Encyclopedia)

To put it bluntly, polymorphism is the same thing, when the same method is called and the parameters are the same, the behavior is different. Polymorphism is divided into two types, one is behavioral polymorphism and object polymorphism.

Polymorphic expression rewriting and overloading.

What is overriding

Overriding: Subclasses can inherit methods in parent classes without Rewrite the same method. But sometimes the subclass does not want to inherit the methods of the parent class unchanged, but wants to make certain modifications, which requires method rewriting. Method overriding is also called method overwriting. (Excerpt from Baidu Encyclopedia)

class Employees {
    constructor(name){
        this.name = name;
    }
    seyHello(){
        console.log("Hello")
    }
    getName(){
        console.log(this.name);
    }
}
class Java extends Employees{
    constructor(name){
        super(name);
    }
    seyHello(){
        console.log(`Hello,我的名字是${this.name},我是做Java工作的。`)
    }
}
const employees = new Employees("Aaron");
const java = new Java("Leo");
employees.seyHello();   //  Hello
java.seyHello();    //  Hello,我的名字是Leo,我是做Java工作的。
employees.getName();    //  Aaron
java.getName(); //  Leo

It can be seen from the above code that Java inherits Employees, but seyHello exists in both the subclass and the parent class. method, in order to meet different needs, the subclass inherits the parent class and rewrites the seyHello method. So you will get different results when calling. Since the subclass inherits the parent class, the subclass also has the getName method of the parent class.

What is overloading

重载就是函数或者方法有相同的名称,但是参数列表不相同的情形,这样的同名不同参数的函数或者方法之间,互相称之为重载函数或者方法。(节选自百度百科)

class Employees {
    constructor(arg){
        let obj = null;
        switch(typeof arg)
        {
            case "string":
                  obj = new StringEmployees(arg);
                  break;
            case "object":
                  obj = new ObjEmployees(ObjEmployees);
                  break;
            case "number":
                obj = new NumberEmployees(ObjEmployees);
                break;
        }
        return obj;
    }
}
class ObjEmployees {
    constructor(arg){
        console.log("ObjEmployees")
    }
}
class StringEmployees {
    constructor(arg){
        console.log("StringEmployees")
    }
}
class NumberEmployees {
    constructor(arg){
        console.log("NumberEmployees")
    }
}
new Employees({})   // ObjEmployees
new Employees("123456") //  StringEmployees
new Employees(987654)   //  NumberEmployees

因为JavaScript是没有重载的概念的所以要自己编写逻辑完成重载。

在上面的代码中定义了Employees,ObjEmployees,StringEmployees,NumberEmployees类,在实例化Employees的时候在constructor里面进行了判断,根据参数的不同返回不同的对应的类。

这样完成了一个简单的类重载。

总结

  1. 封装可以隐藏实现细节,使得代码模块化;

  2. 继承可以扩展已存在的代码模块(类),它们的目的都是为了——代码重用。

  3. 多态就是相同的事物,调用其相同的方法,参数也相同时,但表现的行为却不同。多态分为两种,一种是行为多态与对象的多态。

在编程的是多多运用这个写思想对其编程时很有用的,能够使你的代码达到高复用以及可维护。

相关免费学习推荐:js视频教程

The above is the detailed content of Introduction to the three basic characteristics of object-oriented JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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