Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A brief introduction to the object-oriented of JavaScript and its encapsulation, inheritance and polymorphism

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the object-oriented of JavaScript and its encapsulation, inheritance and polymorphism". In daily operation, I believe that many people have doubts about the object-oriented of JavaScript and its encapsulation, inheritance and polymorphism. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the doubts of "object-oriented of JavaScript and its encapsulation, inheritance, and simple introduction of polymorphism". Next, please follow the editor to study!

Object-oriented and process-oriented

Object-oriented and process-oriented are two different programming ideas. when we first came into contact with programming, we mostly started from process-oriented. after all, like me, most of the computer languages we come into contact with are all C language, and C language is a typical process-oriented computer language.

Process-oriented is mainly based on verbs, and the way to solve the problem is to call different functions step by step in order.

Object-oriented is based on nouns, abstracting the problem into specific objects, and this object has its own properties and methods. When solving problems, different objects are combined and used together.

/ / process-oriented Elephant 1. Open (refrigerator) 2. (elephant) put into (refrigerator) 3. Close (refrigerator) / / object-oriented Elephant 1. Refrigerator。 Open the door () 2. Refrigerator。 Put it into (an elephant) 3. Refrigerator。 Close the door ()

From this example, we can see that object-oriented is based on subject-predicate, subject-predicate can be called an object, and then the object has its own properties and methods.

Object-oriented divides problems by function, not steps. The functional unity ensures the expansibility of object-oriented design and solves the problem of code reusability.

This is also the verification result obtained in the long process of programming development. The idea of object-oriented programming is a little better than process-oriented.

Encapsulation

Object-oriented has three characteristics: encapsulation, inheritance and polymorphism.

Encapsulation: it encapsulates things into classes, hides the implementation details of their properties and methods, and only exposes the interface to the public.

In ES5, there is no concept of class, but because of the function-level scope of js (variables within the function are not accessible outside the function). So we can simulate class. In es5, a class is actually a variable that holds a function that has its own properties and methods. The process of combining properties and methods into a class is encapsulation.

1. Add through the constructor

JavaScript provides a Constructor mode for initializing objects when they are created. A constructor is actually an ordinary function with the following characteristics

① initials are capitalized (it is recommended that the constructor initials be capitalized, even if the big hump is named, but not the constructor initials are lowercase) ② internally uses this ③ to generate instances using new

Adding properties and methods through the constructor is actually the property and method added through this. Because this always points to the current object, the properties and methods added through this are only added on the current object and are owned by the object itself. So when we instantiate a new object, the properties and methods pointed to by this will be created accordingly, that is, a copy will be copied in memory, resulting in a waste of memory.

Function Cat (name,color) {this.name = name; this.color = color; this.eat = (() = > {console.log ("fish!")})} / / generate instance var cat1 = new Cat ("tom", "gray")

Through the properties and methods defined by this, Tawau makes a new copy when we instantiate the object.

two。 Encapsulated through prototype prototype

Adding properties and methods to a class through this will lead to memory waste. Is there any way to make the properties and methods used by the instantiated class directly point to the same property and method using pointers?

This is the method of the prototype.

JavaScript states that each constructor has a prototype property that points to another object. All properties and methods of this object are inherited by the instance of the constructor. That is, for those immutable properties and methods, we can add them directly to the prototype object of the class. Function Cat (name,color) {this.name = name; this.color = color;} Cat.prototype.type = "English short"; Cat.prototype.eat = (() = > {alert ("fish!")}) / / generate instance var cat1 = new Cat ('Tom',' gray') Var cat2 = new Cat ('Kobe',' purple'); console.log (cat1.type); / / English short cat2.eat (); / / fish!

At this point, the type property and the eat () method of all instances are actually the same memory address, pointing to the prototype object, thus improving the running efficiency.

But this also has drawbacks, because the prototypes of instantiated objects all point to the same memory address, and changing the properties of one of the objects may affect other objects.

Classes and wrappers in es6

Es6 declares a class

① constructor: create your own attributes within the constructor

② method: declares the method that the class instance has

Class Cat {/ / is equivalent to the Cat constructor constructor (name) {this.name = name;} / / simpler to declare the inner function of the class / / equivalent to Cat.prototype.eat eat () {console.log ("fish!");}} / / generate the instance var cat1 = new Cat ("tom"); cat1.eat (); / / fish! Console.log (cat1 instanceof Cat); / / true console.log (cat1 instanceof Object); / / true console.log (typeof Cat); / / function console.log (typeof Cat.prototype.eat); / / function

Take the Cat declared by class above as an example: the Cat class is a function with constructor behavior, where the inner method eat is actually Cat.prototype.eat ()

So the class wrapper class of es6 is essentially the syntax sugar of es5 implementation.

The main difference is that the properties of the class class cannot be reassigned and enumerated, and Cat.prototype is a read-only property.

The difference between class and custom types

(1) class's statement will not be promoted, similar to let.

(2) the declaration of class runs automatically in strict mode.

(3) the methods declared by class cannot be enumerated

(4) the internal method of class has no constructor attribute and cannot be new.

(5) the constructor that calls class must be new

(6) class internal methods cannot have the same name

Use of the class class

As a first-class citizen in js, class can be used directly as a value.

/ / 1. The class name is passed as an argument to the function function createObj (ClassName) {return new ClassName ()} / / 2. Execute immediately to implement the singleton pattern let cat1 = new class {constructor (name) {this.name = name} eat () {console.log ("fish!")}} ("tom") cat1.eat () / / fish!

Inherit

Inheritance means that a subclass can use all the functions of the parent class and extend these functions. The process of inheritance is from the general to the special.

1. Class inheritance

Classlike inheritance is the way of using a prototype, adding a method to the prototype of the parent class, and then the prototype of the subclass is an instantiated object of the parent class.

/ / declare the parent class var SuperClass = function () {let id = 1; this.name = ['java']; this.superValue = function () {console.log (' this is supervaluations')}} / / add a common method SuperClass.prototype.getSuperValue = function () {return this.superValue ();} for the parent class / / declare the subclass var SubClass = function () {this.subValue = (() = > {console.log ('this is subValuevalues')})} / / inherit the parent class SubClass.prototype = new SuperClass (); / / add the common method SubClass.prototype.getSubValue = function () {return this.subValue ()} / / generate the instance var sub1 = new SubClass (); var sub2 = new SubClass () Sub1.getSuperValue (); / / this is superValue! Sub1.getSubValue (); / / this is subValue! Console.log (sub1.id); / / undefined console.log (sub1.name); / / ["java"] sub1.name.push ("php"); console.log (sub1.name); / / ["java", "php"] console.log (sub2.name); / / ["java", "php"]

The core of which is SubClass.prototype = new SuperClass ()

The function of the prototype object of the class, the prototype object, is to add common methods to the prototype of the class, but the class cannot access these methods directly. Only after the class is instantiated, the newly created object copies the properties and methods of the constructor of the parent class and points the prototype proto to the prototype object of the parent class. This allows the subclass to access the properties and methods of the parent class, and the properties and methods defined in the parent class are not inherited by the subclass.

But uses the method of class inheritance, and if there is a reference data type in the constructor of the parent class, it will be shared by all instances in the subclass, so if the instance of one subclass changes this reference data type, it will affect the instances of other subclasses.

Constructor inheritance

In order to overcome the shortcomings of class inheritance, there is constructor inheritance. The core idea of constructor inheritance is SuperClass.call (this, id), which directly changes the direction of this so that the properties and methods created by this are copied in the subclass. Because they are copied separately, the instantiated subclasses do not affect each other. But can cause memory waste.

/ / Constructor inheritance / / declare parent class var SuperClass = function (id) {var name = 'java' this.languages = [' java', 'php',' ruby']; this.id = id} / / declare subclass var SubClass = function (id) {SuperClass.call (this, id)} / / generate instance var sub1 = new SubClass (1); var sub2 = new SubClass (2); console.log (sub2.id) / / 2 console.log (sub1.name); / / undefined sub1.languages.push ("python"); console.log (sub1.languages); / / ['java',' php', 'ruby',' python'] console.log (sub2.languages); / / ['java',' php', 'ruby']

Combinatorial inheritance

Combinatorial inheritance absorbs the advantages of both, avoiding memory waste and making each instantiated subclass independent of each other.

/ / Combinatorial inheritance / / declare parent class var SuperClass = function (name) {this.languages = ['java',' php', 'ruby']; this.name = name;} / / declare parent class prototype method SuperClass.prototype.showLangs = function () {console.log (this.languages) } / / declare subclass var SubClass = function (name) {SuperClass.call (this, name)} / / subclass inherit parent class (chained inheritance) SubClass.prototype = new SuperClass (); / / generate instance var sub1 = new SubClass ('python'); var sub2 = new SubClass (' go'); sub2.showLangs (); / / ['java',' php', 'ruby'] sub1.languages.push (sub1.name) Console.log (sub1.languages); / / ["java", "php", "ruby", "python"] console.log (sub2.languages); / ['java',' php', 'ruby']

But warning: combinatorial inheritance is good, but it can cause a problem. The constructor of the parent class will be created twice (again for call () and again for new).

Parasitic combinatorial inheritance

The key to the disadvantage of combinatorial inheritance is that the constructor of the parent class is created on both sides of the combination of class inheritance and constructor inheritance, but in class inheritance we do not need to create the constructor of the parent class. we only need the subclass to inherit the prototype of the parent class.

So we first create a copy of the prototype of the parent class, then modify the constructor property of the subclass, and then set the prototype of the subclass.

/ / prototype inheritance / / prototype inheritance is actually the encapsulation of class inheritance, and the implemented function returns an instance. The prototype of this instance inherits the incoming o object function inheritObject (o) {/ / declare a transition function function F () {} / / the prototype chain inheritance parent object F.prototype = o / / returns an instance of a transition object whose prototype inherits the parent object return new F (); / / parasitic inheritance / / parasitic inheritance is the second encapsulation of prototype inheritance so that the prototype of the subclass is equal to the prototype of the parent class. And in the process of the second encapsulation, the inherited object is extended function inheritPrototype (subClass, superClass) {/ / copy the prototype of the parent class is saved in the variable, so that the prototype of p is equal to the prototype of the parent class var p = inheritObject (superClass.prototype); / / the constructor property of the subclass is modified due to rewriting the prototype of the subclass / / set the subclass prototype subClass.prototype = p;} / define the parent class var SuperClass = function (name) {this.name = name; this.languages = ["java", "php", "python"]} / / define the parent class prototype method SuperClass.prototype.showLangs = function () {console.log (this.languages) } / / define subclass var SubClass = function (name) {SuperClass.call (this,name)} inheritPrototype (SubClass, SuperClass); var sub1 = new SubClass ('go')

Inheritance in es6

Class SuperClass {constructor (name) {this.name = name this.languages = ['java',' php', 'go'];} showLangs () {console.log (this.languages) }} class SubClass extends SuperClass {constructor (name) {super (name)} / / override the method showLangs () {this.languages.push (this.name) console.log (this.languages) in the parent class;}} / / generate instance var sub = new SubClass ('Han Erhu'); console.log (sub.name) / / Han Erhu sub.showLangs (); / / ["java", "php", "go", "Han Erhu"]

Polymorphisms

Polymorphism actually means that different objects act and the same operation produces different effects. Polymorphic thinking actually separates "what you want to do" from "who will do it".

The advantage of polymorphism is that you no longer have to ask the object "what type are you" and then invoke a behavior of the object based on the answer you get. Feel free to invoke this behavior, and everything else can be handled by polymorphism. In terms of specification, the most fundamental function of polymorphism is to eliminate these conditional branch statements by transforming procedural conditional statements into object polymorphism.

Since there are not many details on polymorphism mentioned in JavaScript, here is a simple example to introduce.

/ / Nonpolymorphic var hobby = function (animal) {if (animal = = 'cat') {cat.eat ()} else if (animal = =' dog') {dog.eat ()} var cat = {eat: function () {alert ("fish!")}} var dog = {eat: function () { Alert ("meat!")}} console.log (123) Hobby ('cat'); / / fish! Hobby ('dog'); / / meat!

As can be seen from the above example, although the hobby function currently maintains a certain degree of flexibility, this flexibility is very fragile. Once you need to replace or add other animal, you must change the hobby function and continue to pile conditional branch statements into it. We abstract the same part of the program, which is to eat something. And then reprogram it.

/ / Polymorphic var hobby = function (animal) {if (animal.eat instanceof Function) {animal.eat ();}} var cat = {eat: function () {alert ("fish!")}} var dog = {eat: function () {alert ("meat!")}

Now let's look at the polymorphism in this code. When we send an eat message to the two types of animal, their eat methods are called respectively, resulting in different execution results. The polymorphism of the object reminds us that "what to do" and "how to do it" can be separated, so the code is much more resilient. Even if other animal,hobby functions are added later, nothing will be changed.

/ / Polymorphic var hobby = function (animal) {if (animal.eat instanceof Function) {animal.eat () } var cat = {eat: function () {alert ("fish!")}} var dog = {eat: function () {alert ("meat!")}} var aoteman = {eat: function () {alert ("lil-monster!")}} hobby (cat); / / fish! Hobby (dog); / / meat! Hobby (aoteman); / / lil-monster! At this point, the study on "object-oriented of JavaScript and its encapsulation, inheritance, and brief introduction of polymorphism" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report