JavaScript Object-oriented journey (bottom)

Source: Internet
Author: User

JavaScript Object-oriented journey

Cut constantly, the reason is disorderly, is parting.

The two steps of the new language development are as follows: first, defining the basic data types, perfecting the design of the structured programming language; second, the concept of binding this for a function type, fortunately, can be referenced to the object itself in the object's method. The following is a continuation of the idea, the main idea is to refer to the traditional object-oriented language related concepts (such as class, inheritance, etc.) to the new language.

Third, let the object belong to a class

This time we are going to introduce the concept of class. Note, however, that the idea mentioned earlier is to make an object appear to belong to a class rather than to actually construct a variety of semantic concepts based on the class.

In general, classes include class symbols and class templates. The simplest class symbol can be a string property. For example, any object, its class attribute to indicate the class name, called Obj.class returns the class name string (such as "Cat", "Dog", etc.). But the trouble is the class template. We want to define the class template in a uniform place so that the class instance is created in a uniform pattern. This creates a class instance (that is, an object) that is really meaningful. Because we not only have to differentiate classes in class notation, but more importantly, to unify classes in class behavior.

The thought of this is a function. Because in JavaScript, the creation of all objects is done through a block of code, and the function can combine this block of code together. Therefore, a generic function can be defined as a class template, and further, it is considered a construction method.

The general function definition is:

function createStudent(name, age) {var student = {};student.name = name;student.age = age;student.toString = function() {return this.name + " " + this.age;};student.class = ‘Student‘;return student;}

In this way, we can fully express some of our previous concepts. Moreover, this approach does not introduce any new language concepts. However, this construction is entirely dependent on the developer to implement. The language itself does not automatically support any of these concepts.

As a result, the JavaScript designers at the time pushed further into the language itself to implement some concepts automatically. It is divided into the following steps:

1. Introduction of the concept of a constructor function

The createstudent above are more or less like the constructor. Object-oriented languages like Java and C + +, when the constructor is called, the object is created. The constructor completes some of the initialization work. There is no need to create objects as shown in the 2nd line of code. So, the previous code should be rewritten like this:

function Student(name, age) {this.name = name;this.age = age;this.toString = function() {return this.name + " " + this.age;};}

Here are some of the main changes:

1. 函数名不再是createStudent,而是Student,这看起来更像是构造函数的名字。2. 不再显示地创建对象;而是当函数作为构造函数调用时,会默认构造一个空对象,并能够通过this访问。3. 函数不再return返回任何对象;而是默认地,应该返回this指向地对象。4. 不再有任何显示地构造this.class = "Student"之类的语句;而是默认地,这一构建应该在构造过程中自动完成。

However, it is said here that it is necessary to do some work to achieve this series of changes. If you also call the student function as before, the above mentioned four point effect (said wrong, in fact, the 1th effect reached). Interested students can take a self-guessing.

To achieve the four-point effect mentioned above, the JavaScript designer introduces a new statement. It is called as if it were a Java construction object. Like the following:

new Student("Sam", 18);

While the above statement actually does the work, the JavaScript description is roughly the following:

var obj = {};Student.call(obj, "Sam", 18);obj.i_was_build_by = Student;return obj;

This particular note is the third line of code. Instead of distinguishing the object's class by adding a class attribute, we add a i_was_build_by property that references the constructor student. This is equivalent to the previous class attribute, but it does not refer to a simple string, but to a function. That's OK. We can also make a similar decision about whether an object belongs to a class:

instanceof Student //等效于 s.i_was_build_by == Student

I write such a wonderful name, I do not want to mislead the reader. If you want to pursue it, JavaScript does not differentiate the object in this way, its mechanism is slightly more complex, but the general idea is the same.

Let the method define only once

We see the changed code, which still has a disadvantage. In a class-based language, a method belongs to a class and needs to be defined only once. In our version, the method belongs to the object, which is defined once each time the student function is called. And not to mention the memory consumption that comes with it. It's a bit worse to look like Java. So here's another change, so the method needs to be defined only once.

The

idea is to keep an object reference to the newly created object, which contains a collection of methods for the class to which the object belongs. First, the name of the reference is prototype, and secondly, its source is a reference to the constructor with the name prototype; Finally, all methods not found in this object are pushed into prototype to find. For example, we would like to write the previous case as follows:

function Span class= "Hljs-title" >student (name, age) {this.name = name;< Span class= "Hljs-keyword" >this.age = Age;} Student.prototype.toString = function  () {return this.name + this.age;}; var s = new Student ();  S.prototype = = Student.prototype; //s.tostring () = = S.prototype.tostring.call (s);       

Explanation: The student function itself has a property prototype. An S object constructed from the new Student () statement whose prototype property points to the prototype property of the function Student. Finally, when S.tostring () is called, because the ToString property does not exist in S, it jumps to the prototype object to find it. As if the attributes in the prototype are their own.

So really the new Student ("Sam", 18) statement execution logic can be summarized as follows:

var obj = {};Student.call(obj, "Sam", 18);obj.i_was_build_by = Student;obj.prototype = Student.prototype;return obj;

In this way, we can only define the method once at prototype, and prototype can also define the common properties of the class. This is the function of the prototype place. We will also see that through the prototype chain, it also opens the way to the door of inheritance.

Four, inheritance is not mysterious, it is prototype chain

It's almost finished. Perhaps the most memorable part of JavaScript is inheritance. But I'm a little tired of writing, here no more mention.

The idea is to expand prototype down. As we mentioned before, if an object's properties cannot be found, it will be found in its prototype reference, if it is not found in the prototype reference. Then it will be found in the prototype reference referenced by prototype, until it is found or the prototype reference is empty.

But what is this connection to inheritance? In fact, the effect of inheritance can be achieved by cleverly structuring the prototype chain. Inconvenient to say, on the example bar:

function Animal() {}function Dog() {}Dog.prototype = new Animal();

This implements the magic of inheritance. At first glance may not understand, need to disassemble:

let animal = new Animal();animal.prototype == Animal.prototype;let Dog.prototype = animal;let dog = new Dog();dog.prototype == Dog.prototype == animal;

The above example shows that if you create a new dog object, its prototype object (taking a middle variable for the moment) is animal, and the prototype object of the animal object will go back to animal. For a method call to dog, it is first searched for in the animal (this is the dog's prototype), and if it is not, it will be found in the prototype of animal (this is animal prototype). In this way, we can call not only the methods defined in Dog.prototype (which are the methods of subclasses), but also the methods of Animal.prototype (this is the method inherited from the parent class). This allows for inheritance.

V. Summary

JavaScript is created almost as it is. This idea is almost an overview of JavaScript object-oriented. In fact, JavaScript really has a more complex internal mechanism than this, but I believe it has its own considerations. In short, JavaScript has its own object-oriented thinking, but also the introduction of the traditional class-based template-oriented concept came in, it becomes now.

Category: My JavaScript Series Tags: JavaScript, object oriented

JavaScript Object-oriented journey (bottom)

Related Article

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.