Native javascript object-oriented analysis and reflection

Source: Internet
Author: User
Tags inheritance reflection

Object-oriented language has three features: encapsulation, inheritance, and polymorphism. Js beginners generally think that JavaScript is the same as other C languages. Keywords like Class can help us better perform object-oriented operations in js. But this is not the case.

Strictly speaking, js is not an object-oriented language, but we can use some advanced features in js for OOP programming.

 
---- Encapsulation

In js, how do I create an object? This is very simple. We only need to create a new encapsulated function (class in C language) to instantiate an object.

First, we will construct such a "class". Before constructing a class, we must know that a class must have "variables" and "methods". Then we will construct this "class ":

Function Parent (){
This. name = "Parent ";
This. sayName = function (){
Console. log (this. name );
    }
}
Var p1 = new Parent ();
P1.sayName ();

How are you doing? In this way, a "class" is encapsulated. However, this class looks very cumbersome, because the name is fixed, so we need to modify and extend it.

Function Parent (name ){
This. name = name;
This. sayName = function (){
Console. log (this. name );
    }
}
Var p1 = new Parent ("yxy ");
P1.sayName (); // Print yxy on the console

In this way, the encapsulated "class" becomes variable, method, external parameter, and reusable. Does it look perfect?

Try this. Each time you create an object, a variable is created, and a method is also created. This method only works for the same method for all objects. Why do you need to create this method multiple times? People who have learned java or c ++ may think, how do you know that this method has been created multiple times, not the same one referenced? Hmm? Let's do a test.

Function Parent (name ){
This. name = name;
This. sayName = function (){
Console. log (this. name );
    }
}
Var p1 = new Parent ("yxy ");
Var p2 = new Parent ("danshengou ");
Console. log (p1.sayName = p2.sayName); // false

Using "=", we can see that the two methods are different, that is, they are created multiple times. So after we create multiple objects, every method of each object is different! This obviously consumes a lot of memory and is not conducive to web development. How can this problem be solved?

The "classes" in js I mentioned in the previous article are all double quotation marks. The reason is very simple. js does not support classes (which can be supported in ES6 specifications), but for convenience, we can call it a "pseudo class ". But in our previous examples, it cannot be said to be a pseudo class! Because there is no way to reuse it, isn't it? Next we will introduce a very conceptual term: "prototype ".

Prototype. Each function has a prototype attribute, which is a pointer pointing to an object, the purpose of this object is to include attributes and methods that can be shared by all instances of a specific type. It is really hard to understand. In short, the prototype attribute is the prototype object of the object instance created by calling the constructor. If you do not know, I recommend that you take a good look at Chapter 6 of <javascript advanced programming>.

Remember why we need to use the prototype in the encapsulation. If you are still confused about the concept of prototype, first understand the benefits of using it. The advantage of using a prototype is that all object instances can share its attributes and methods. Seems much clearer? Let's modify the example mentioned above.

Function Parent (name ){
This. name = name;
}
Parent. prototype. sayName = function (){
Console. log (this. name );
}
Var p1 = new Parent ("yxy ");
P1.sayName (); // call the sayName method in the prototype to print the yxy
Var p2 = new Parent ("danshengou ");
Console. log (p1.sayName = p2.sayName); // true
Console. log (p1.sayName === p2.sayName); // true

In this example, we construct a function in prototype mode. We instantiated two objects, compared their values and addresses with "=" and "=", and found they are the same. It seems that the prototype is really useful, which greatly saves our memory space. You may ask, why don't you put the variables in the prototype? Because the prototype is shared by all objects, the attributes of each object must be held by the object itself. If they are placed in the prototype, there is no difference between these objects. This is what we call "combination inheritance ".

So far, we have successfully created a perfect js "pseudo class. And you should have a great understanding of the prototype.

---- Inheritance

After you understand the entire encapsulation process, you may be very disappointed with js. Since there is such a complicated encapsulation, it is certainly difficult to inherit.

However, the inherited syntax is actually very simple.

Let's take a look at Inheritance:

Function Parent (name ){
This. name = name;
}
Parent. prototype. sayName = function (){
Console. log (this. name );
}

Function Child (name, position ){
This. position = position;
Parent. call (this, name );
}
Child. prototype = new Parent ();
Child. prototype. sayPos = function (){
Console. log (this. position );
}

Var p1 = new Child ("yxy", "student ");
P1.sayName ();
P1.sayPos ();

There are two ways to attract our attention.

1. Parent. call (this, name)
2. Child. prototype = new Parent ();

In detail, it may be easy to get dizzy. I start with the concept of inheritance. First, the sub-object inherits the variables and methods of the parent object. We can clearly see from the code scope that Parent. call (this, name) is obviously inheriting variables in the constructor. Child. prototype = new Parent (). This Parent object is created without parameters. It is obviously inheriting the prototype. Is it easy to understand?

Child. prototype = new Parent (). This statement is very simple and I will not elaborate on it. Here we will focus on Parent. call (this, name.

Parent. call (this, name) has several other methods:

1. Parent. call (this, arguments [0]);
2. Parent. apply (this, [name]);
3. Parent. apply (this, arguments );

Although the four write methods are different, the effects are the same: reference the context of the parent class constructor to the constructor context of the subclass.

Call and apply can be used to call a method instead of another object. The two can change the object context of a function from the initial context to the new object specified by this. Is it a bit difficult? Simply put, this object executes a Parent function in the current context and passes the parameter (the parameter after this) to the Parent function.

We all know how a function exposes its internal attributes, that is, it can be accessed in its parent scope once it is executed. Then, to understand this apply, the mechanism of call is very simple.

The inheritance syntax is simple, but the inheritance mechanism still takes time to understand.

Finally, we gave the js object-oriented step a very detailed one. Maybe everyone thought they could finally start to simulate some difficult object-oriented instances. This time I will not oppose everyone, but didn't you see anything missing? Run the following code:

Function Parent (name ){
This. name = name;
}
Parent. prototype. sayName = function (){
Console. log (this. name );
}

Function Child (name, position ){
This. position = position;
// Parent. call (this, name );
Parent. apply (this, [name]);
}
Child. prototype = new Parent ();
Child. prototype. sayPos = function (){
Console. log (this. position );
}

Var p1 = new Child ("yxy", "student ");
Console. log (p1.name); // yxy
Console. log (p1.position); // student

Hmm? I obviously want to privatize the variables, but why can I access them? Careful people may have long thought of it when inheriting that part. As long as a function is executed, My variables and methods will be exposed! In fact, this is not encapsulation at all! It's just installation.

That's right. js does not have private and public keywords to define the private and public properties of attributes and methods. You may be very disappointed and disappointed. If you have done so much in the past, you will get a half-blind object-oriented. In fact, not only do you think so, many developers also think that they use complicated names to name some variables to ensure that they are not so easy to access. This is a way, but there is no other way?

If you think about it, how can we simulate private and public operations? I will give an example and a concept, and then you can start to think about js's real object-oriented thinking.

Concept: "module mode"

Code:

Var Parent = function (name, publicAge ){
Var myName = name;
Return {
Age: publicAge,
SayName: function (){
Console. log (myName );
        }
};
};

Var p1 = Parent ("yxy", "20 ");
P1.sayName (); // yxy
Console. log (p1.age); // 20
Console. log (p1.myName); // undefined

When you can understand the access level in encapsulation, the real thinking of javascript is just getting started.



Is object-oriented thinking in JavaScript really important?

Specifically, how can we use object-oriented JavaScript to construct a website's front-end architecture?

Recently, many people have mentioned the object-oriented programming of JavaScript. Many methods and skills for implementing object-oriented programming in JavaScript are introduced on the internet. I also know some of them, however, every time it comes to actual development, object-oriented js development is rarely used. It may be that you are not very familiar with the real object-oriented thinking, I am not very familiar with some OO design patterns.

I really want to know whether the JavaScript object-oriented development idea is really important when developing the front-end, and how to use it in development.


The concept of object-oriented has been around for a long time. Any language can be object-oriented. There are many reasons for using object-oriented programming, but I personally think there are two advantages in front-end development. First, we need to integrate loose JS code to facilitate later maintenance. Second, we need to adapt our code to more business logic. These two points are my deep experience in my daily work. To put it bluntly, in the front-end development process, the things we are most exposed to are actually various businesses. In my opinion, every business is an object, these services must be composed of small functions. Therefore, as I understand, Object-oriented means constructing corresponding statuses and operations for this service. On this premise, we can continue to subdivided and constructed the following small functions. To achieve this goal, we usually adopt methods such as encapsulation, inheritance, and polymorphism. Finally, in the application process, you can use OO to obtain the status and methods to implement the business. (For example, the object-oriented and process-oriented interfaces sometimes exist alternately or even complement each other) ============================================ above ?? Aluminum torn? What is the root of the humble spine? Fading walls? Why is it true? Why is it possible to drop the network ?? Ü? Juaier? Altar school? Why? Why ?? Harmony between neon, dizheng? Banter? School discussion? Ü? Why ?? What is it? Do you have a Yanyun yundun? Head pepper commissioning? Too many? The process-oriented approach is to sort out your business logic in sequence, consider every small logic as a module, and apply an object-oriented approach. This is what I understand and how to apply it to the answer to the question of development.


I think object orientation at the front end is not so important. It is not so important ], or there is no need to [deliberately] pursue the biggest feature of object-oriented objects. It is nothing more than "inheritance, polymorphism, encapsulation, and combination". Let's look at an object-oriented language or framework, the first response is how inheritance and polymorphism are implemented. But in the front-end environment, is the benefits of inheritance and polymorphism really high? Back to the source of the problem, the starting point of inheritance and polymorphism is "separation of concerns ". Make the program adapt to the "focus" changes at minimal cost. However, the difference between the front-end environment and the back-end is that the back-end program only has "data + behavior" and has little focus and is easy to predict. The front-end is "data + behavior + Display + interaction". The Extra "Display + interaction" determines that the front-end has many concerns and cannot be predicted, unless manual attention is limited, the UI framework, which allows the UI and interaction to be completely embedded in a relatively dead range, has several common features: "ugly, slow, and big ", in combination with the above analysis, it is not difficult to understand that for the front-end, it is very necessary to do a good job of code layering, decoupling, and structuring, but it is not necessarily related to the pursuit of object-oriented.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.