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

How to understand the object-oriented in JS

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to understand the object-oriented in JS". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand the object-oriented in JS".

Before we talk about this, let's talk about class. Anyone who knows about object-oriented should know that if I want to define a generic type, I can use class. For example, in java we can define a class like this:

Public class Puppy {int puppyAge; public Puppy (age) {puppyAge = age;} public void say () {System.out.println (woof);}}

The above code we define a Puppy class, this class has a property is puppyAge, that is, the dog's age, and then there is a constructor Puppy (), this constructor takes a parameter, you can set the dog's age, and there is a speaking function say. This is a general class, which is written directly when we need a two-year-old puppy instance, which also has the method of the parent class:

Puppy myPuppy = new Puppy (2); myPuppy.say (); / / Wang Wang

But the early JS does not have the class keyword (the following said that JS without the class keyword refers to the JS before ES6, mainly to help people understand the concept, this article does not involve the class of ES6), JS in order to support object-oriented, used a more tortuous way, which is also cause everyone confusion, in fact, we compare this way with the general object-oriented analogy is very clear. Let's take a look at what problems JS needs to solve in order to support object-oriented, and what tortuous ways to solve them.

There is no class, use functions instead

First of all, JS doesn't even have the class keyword. What should I do? Instead of functions, the most important thing in JS is the function, which can not only perform ordinary functions, but also can be used as class. For example, we are going to use JS to build a puppy class. Just write a function:

Function Puppy () {}

This function can generate an instance directly with the new keyword:

Const myPuppy = new Puppy ()

So we also have an example of a puppy, but we don't have a constructor and we can't set the age of the puppy.

The function itself is the constructor

The function used as a class is itself a function, and it is the default constructor. We want the Puppy function to be able to set the age of the instance, as long as it receives parameters.

Function Puppy (age) {this.puppyAge = age;} / / the age parameter can be passed when instantiating const myPuppy = new Puppy (2)

Notice the this in the above code, where this always points to the instantiated object, that is, myPuppy, as a function used by the class. The purpose of this design is to allow the user to set properties to the instance object through the constructor, and then console comes out to see

MyPuppy.puppyAge is 2. Console.log (myPuppy.puppyAge); / / output is 2

The example method uses prototype.

Above we implemented the class and constructor, but what about the class method? The Java version of the puppy can also bark, what about the JS version? The solution given by JS is to add a prototype attribute to the method, and the method mounted on it will be given to the instance object when instantiated. If we want myPuppy to be able to speak, we need to add a way to speak to Puppy.prototype.

Puppy.prototype.say = function () {console.log ("woof");}

All the instances generated using the new keyword have properties and methods on the prototype of the class. We added the say method to the Puppy.prototype, and myPuppy can talk. Let's try it:

MyPuppy.say () / / woof.

Use _ _ proto__ for instance method search

So how can myPuppy call the say method? let's print it out and see that there is no say on this object. Where did it come from?

It's time for _ _ proto__ to play. When you access a property that is not available on an object, such as myPuppy.say, the object will go to _ _ proto__ to look for it. The value of _ _ proto__ is equal to the prototype of the parent class, and myPuppy.__proto__ points to Puppy.prototype.

If the attribute you visit does not exist in Puppy.prototype, you will continue to look for Puppy.prototype.__proto__. At this time, you will find Object, and Object will not find it again, that is, null, which is actually the prototype chain.

Constructor

When we say constructor, we generally refer to the prototype.constructor of the class. Prototype.constructor is a reserved attribute on prototype, which points to the class function itself and indicates the constructor of the current class.

Since prototype.constructor is a pointer to the constructor, can we use it to modify the constructor? Let's try and find out. Let's modify this function first, and then create a new instance to see the effect:

Function Puppy (age) {this.puppyAge = age;} Puppy.prototype.constructor = function myConstructor (age) {this.puppyAge2 = age + 1;} const myPuppy2 = new Puppy (2); console.log (myPuppy2.puppyAge); / / output is 2

The above example shows that we only modified the pointer by modifying prototype.constructor, not the real constructor.

Some friends may say that I print myPuppy2.constructor is also worth ah, then constructor is also an attribute of the object itself? Actually, no, the reason why you can print out this value is because when you print, you find that myPuppy2 itself does not have this attribute, and you look for it on the prototype chain and find prototype.constructor. We can use hasOwnProperty to take a look at it:

We have actually explained the relationship between prototype,__proto__,constructor above, so let's draw a picture to take a more intuitive look:

Static method

We know that many object-oriented objects have the concept of static methods. For example, Java can define a method as a static method by simply adding a static keyword. It is easier to define a static method in JS, just make it a property of the class function:

Puppy.statciFunc = function () {/ / statciFunc is a static method conlose.log ('I am a static method, this cannot get the instance object');} Puppy.statciFunc (); / / is called directly through the class name

The main difference between the static method and the instance method is that the instance method can access the instance and operate on the instance, while the static method is generally used for instance-independent operations. These two methods are widely used in jQuery. In jQuery, $(selector) actually gets the instance object, and the method that operates through $(selector) is the instance method. For example, $(selector). Append (), which adds a new element to the instance DOM. He needs this DOM instance to know how to operate. If append is used as an instance method, the this in it will point to this instance, and you can manipulate the DOM instance through this. So what method is suitable as a static method? For example, $.ajax, the ajax here has nothing to do with the DOM instance. You don't need this this. You can mount it directly on $as a static method.

Inherit

How can object-oriented not inherit? according to the knowledge mentioned above, we can actually write an inheritance by ourselves. Doesn't inheritance mean that a subclass can inherit the properties and methods of the parent class? In other words, the subclass can find the parent class's

Prototype, the easiest way is to point the _ _ proto__ of the subclass prototype to the parent prototype. Function Parent () {}

Function Child () {} Child.prototype.__proto__ = Parent.prototype; const obj = new Child (); console.log (obj instanceof Child); / / true console.log (obj instanceof Parent); / / true

The above inheritance method only gives Child access to the Parent prototype chain, but does not execute the constructor of Parent:

Function Parent () {this.parentAge = 50;} function Child () {} Child.prototype.__proto__ = Parent.prototype; const obj = new Child (); console.log (obj.parentAge); / / undefined

In order to solve this problem, we can not simply modify the Child.prototype.__proto__ point, but also need to use new to execute the constructor of Parent:

Function Parent () {this.parentAge = 50;} function Child () {} Child.prototype.__proto__ = new Parent (); const obj = new Child (); console.log (obj.parentAge); / / 50

The above method will have an additional _ _ proto__ level, which can be solved by changing the direction of the Child.prototype. Please set the

Child.prototype.constructor reset back: function Parent () {this.parentAge = 50;} function Child () {} Child.prototype = new Parent (); ChildChild.prototype.constructor = Child; / / Note reset constructor const obj = new Child (); console.log (obj.parentAge); / / 50

Of course, there are many other ways of inheritance, their principles are similar, but the implementation is different, the core is to let the subclass have the methods and properties of the parent class, interested friends can consult.

Implement a new by yourself

Combined with the above, we know that new actually generates an object that can access the prototype of the class. Knowing the principle, we can implement a new ourselves.

Function myNew (func,... args) {const obj = {}; / / create a new empty object func.call (obj,.. ARGs); / / execute the constructor obj.__proto__ = func.prototype; / / set prototype chain return obj;} function Puppy (age) {this.puppyAge = age } Puppy.prototype.say = function () {console.log ("Wang Wang");} const myPuppy3 = myNew (Puppy, 2); console.log (myPuppy3.puppyAge); / / 2 console.log (myPuppy3.say ()); / / Wang Wang

Implement an instanceof by yourself

We know the principle, but in fact we also know what instanceof does. Isn't instanceof all about checking whether an object is an instance of a class? In other words, check whether there is a prototype of this class on the prototype chain of an object. Knowing this, we can implement one ourselves:

Function myInstanceof (targetObj, targetClass) {/ / Parameter check if (! targetObj | |! targetClass | |! targetObj.__proto__ | |! targetClass.prototype) {return false;} let current = targetObj; while (current) {/ / always look for if (current.__proto__ = = targetClass.prototype) {return true on the prototype chain. / / returned true} currentcurrent = current.__proto__;} return false; / / not found returned false} / / using our previous inheritance experiment under function Parent () {} function Child () {} Child.prototype.__proto__ = Parent.prototype; const obj = new Child (); console.log (myInstanceof (obj, Child)) / true console.log (myInstanceof (obj, Parent)); / true console.log (myInstanceof ({}, Parent)); / / false Thank you for your reading, the above is the content of "how to understand the object-oriented in JS". After the study of this article, I believe you have a deeper understanding of how to understand the object-oriented in JS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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