Home Web Front-end JS Tutorial javascript object-oriented encapsulation and inheritance_javascript skills

javascript object-oriented encapsulation and inheritance_javascript skills

May 16, 2016 pm 04:30 PM
javascript encapsulation inherit object-oriented

Let’s sort out the encapsulation and inheritance in js object-oriented.

1. Encapsulation
There are many ways to implement encapsulation in js. Here are some commonly used ones.

1.1 Original mode generation object
Directly write our members into the object and return them with the function. Disadvantages: It is difficult to see an instance of a pattern.

Code:

Copy code The code is as follows:

function Stu(name, score) {
             return {
name: name,
score: score
            }
}
        var stu1 = Stu("张三", 80);
        var stu2 = Stu("李思", 90);
console.log(stu1.name); // Zhang San

1.2 Generating construction pattern objects

js provides us with a pattern of using constructors to generate objects. The so-called "constructor" is actually an ordinary function, but the this variable is used internally. When the new keyword is used to generate an instance of the constructor, the this variable will be bound to the instance object.

Directly enter the code:

Copy code The code is as follows:

Function Stu(name, score) {
This.name = name,
This.score = score
}
        var stu1 = new Stu("张三", 80);
        var stu2 = new Stu("李思", 90);
console.log(stu1.name "/" stu2.score); // Zhang San 90
console.log((stu1.constructor == Stu) "/" (stu2.constructor == Stu)); // true true
console.log((stu1 instanceof Stu) "/" (stu2 instanceof Stu)); // true true

It is not difficult to see that the object generated by the js constructor is exactly the same as the object generated by class in C#. Both use templates to define object members and instantiate them through the new keyword.

Generate the same Stu object using C# code

Copy code The code is as follows:

Class Stu
{
​public string name;
  public double score;     
}

OK, now we have the basic objects. So now we need a method that is common to all objects, and only allows this method to be created once. (Not created repeatedly with object new) What should I do? Everyone knows that in C# we can use static members. So how to do it in js?

1.3 Prototype Mode

In js, each constructor has a prototype attribute. All properties and methods of this object will be inherited by the instance of the constructor. Then adding members directly to the prototype is equivalent to declaring static members in C#.

Code:

Copy code The code is as follows:

Function Stu(name, score) {
This.name = name,
This.score = score
}
Stu.prototype.type='Student';
Stu.prototype.log = function (s) {
console.log(s);
}
        var stu1 = new Stu("张三", 80);
        var stu2 = new Stu("李思", 90);
console.log(stu1.type "/" stu2.type); // Student Student
          stu1.log('hello'); // hello
console.log(stu1.log == stu2.log); // true

That’s it for encapsulation. Let’s take a look at how inheritance is implemented in js?

2. Inheritance

2.1 Constructor Binding

Directly call the call or apply method in the child function to bind the parent object’s constructor to the child object.

Copy code The code is as follows:

function Stu(name, score) {
Grade.apply(this, arguments);
//Grade.call(this, arguments);
This.name = name,
This.score = score
}
         function Grade() {
This.code = "Junior High School";
This.ask = function () {
console.log("Hello everyone");
            }
}
        var stu1 = new Stu("张三", 80);
        var stu2 = new Stu("李思", 90);
console.log(stu1.code); // Junior High School
          stu1.ask(); // Hello everyone

The apply here does two things. It gives the first parameter this to the Grade constructor (caller), and then executes the code in Grade. It is equivalent to executing the members defined with this in Grade again in Stu.

2.2 Inheritance through prototype
​Look at the code first

Code:

Copy code The code is as follows:

Function Stu(name, score) {
This.name = name,
This.score = score
}
         function Grade() {
This.code = "Junior High School";
}
Stu.prototype = new Grade();
Stu.prototype.constructor = Stu; //Prevent inheritance chain disorder and manually reset the statement
        var stu1 = new Stu("张三", 80);
        var stu2 = new Stu("李思", 90);
console.log(Stu.prototype.constructor); // Own constructor
console.log(stu1.code); // Junior High School

As mentioned before, prototype is equivalent to a static member in C#, so we turn all members of the parent class into our own static members to achieve inheritance.

There is a disadvantage of inheritance through prototype: all inherited members are static, so how to inherit object members?

2.3 Copy inheritance

Copy all properties and methods of the parent object into the child object to achieve inheritance.

Code:

Copy code The code is as follows:

Function Stu(name, score) {
This.name = name,
This.score = score
}
function Grade() {}
Grade.prototype.code = "Junior High School";
}
//Function encapsulation
function extend(C, P) {
            var p = P.prototype;
          var c = C.prototype;
for (var i in p) {
                    c[i] = p[i];
            }
}
extend(Stu, Grade);
        var stu1 = new Stu("张三", 80);
        var stu2 = new Stu("李思", 90);
          stu1.code='High School';
console.log(stu1.code); // High School
console.log(stu2.code); // Junior High School
console.log(Stu.prototype.constructor);
console.log(Grade.prototype.constructor)

That’s it for the js object-oriented organization. This thing is not static. You can make changes according to your own needs when using it. There is a saying that is very good, the right one is the best.

Here we only analyze encapsulation and inheritance. We will do some other articles in the future to give you a deeper understanding of JavaScript object-oriented programming. Of course, these are all personal understandings. If there are any omissions, please contact me.

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

Video Face Swap

Video Face Swap

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

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)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

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.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

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

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

See all articles