Object inheritance relationships in JavaScript

Source: Internet
Author: User

I believe that every student who has studied other languages will feel a lot of difficulties when they learn JavaScript.

This is really a language to subvert our previous programming ideas, not to mention its various data types and expressions

The difference, the most headache, I am afraid is the object-oriented part, in JavaScript, is not given a

Create an object, unlike a class in Java, it can create an object, in JavaScript,

The object is a very loose combination of key-value pairs, which, in general, can be created by {} When we create the object.

Delivered into an object, as we have learned before, objects have attributes, there are behaviors, here we call methods, then we

Let's start by creating an object:

var Zhangsan ={name: "Zhang San", age:14}

This is a simple object, the advantage of this way is simple and direct, one can see his properties and methods

However, the disadvantage of this method is also obvious, when we want to create more than one object, we need one to create,

One-to-one assignment, which is a cumbersome and less-visible method, we can use the factory method to create:

1 functionCreatepeople (name,food) {2     varPeople =Newobject ();3People.name=name;4people.eat=function(food) {5 alert (food);6      }7     returnpeople;8 }9 varZhangsan=createpeople ("Zhangsan", "tofu");TenZhangsan.eat ();//This will pop up tofu.

This method can create multiple objects, in a vulgar way, that is, how many people you want to build,

Haha, so you think this is a good way to create objects? Wrong, now we have another problem, is that I

We are now using this factory method, you do not know what kind of class you created, you created the people in the final knot

The bottom is created by the new object (), and the method of defining a class in a literal way is not fundamentally different.

Similarly, I can create a dog, a cat, an elephant, a bench, and so on, in this way, the meaning of the class.

What else is necessary, at this point, there is a way to create the class using the constructor method see Code 2:

1 functionCreatepeople (name,age,food) {2      This. name=name;3      This. age=Age ;4      This. food=Food ;5      This. eat=function(){6Alert This. name+ "Love to eat" + This. Food;7     }8 }9 varZhangsan =NewCreatepeople ("Zhang San", 13, "tofu");TenZhangsan.eat ();//This is going to pop up the three love tofu this sentence

In this way, we can avoid the kind of situation where we don't know what type of object is being created, which

We're going to introduce the construction method to create the object, if not add new,createpeople () is just a very common

function, but after adding new to it, it's all going to be different, and the sentence in line nineth in code 2 can be broken down

For two words to understand:

1 var zhangsan={}; // The first step is to create an empty object, 2 createpeople.apply (Zhangsan arguments); // This step binds the this in the function to Zhangsan, and then the code in the execution function

Well, using a constructor to create an object, we can think of this function as a class that can create a class that belongs to it.

As opposed to a factory method like the one above, each object has no clear classification, understanding JavaScript memory management Wit

We should all know that in JavaScript, every time you create an object, the methods and properties of the object are in the heap.

Allocate a memory space, but for many objects, their properties are mostly different, but many times they are very

Many methods are the same, the difference is only the parameters of the different, it is very wasteful of our memory, this time,

Let's start by understanding the prototype chain of the object:

Within each function, there is a prototype property that executes their prototype object, and the prototype property

Each function has a constructor attribute in the ProtocolType object, which points to the function itself,

So the question is, this is a very round-off problem, so let's take a look at the picture:

So what do you mean by the way I've created each object? Of course, there is a relationship, and when we use the new constructor to create an object, the object we create will also have a _proto_ property that points to the constructor's prototype object, which means Between our object instances and the constructors, they all point to the object prototype, and we can inherit the properties and methods in the constructor prototype object in each of our objects. Then this leads us to the point that we are going to put the method we need for each object into our prototype object:

1 functionCreatepeo (username,hobby) {2      This. username=UserName;3      This. hobby=Hobby;4createpeo.prototype.eat=function(){//to save memory by defining functions on the object prototype;5Alert This. username+ "Like to eat" + This. Hobby);6     }7 }8 varShang =NewCreatepeo ("Zhang Shan", "Chow Mein");9 varLiSi =NewCREATEPEO ("John Doe", "string");//This can greatly save our memory, and each object can be called to our method.

OK, now that we have successfully created a class, and by this class to create the objects I need, then we all know that with the class, with the object, we will always subconsciously go back, tired of the three characteristics: encapsulation, inheritance, polymorphism, then in JavaScript, How is the encapsulation of classes implemented? We'll talk about it tomorrow when we talk about closures, and today we'll discuss the inheritance in classes, and in our JavaScript, the inheritance of classes is not as class...extend as in Java. In JavaScript, we do not have a class inheritance concept, we use a very random prototype chain of execution inheritance, that is, through the prototype property to point to the object to inherit the prototype object, then we began to think, So I'm just going to use the prototype attribute to point to the line?

1 function Dog (name,age) {2     this. name=name; 3     this. age= age; 4 }5function  Littledog () {}6 littledog.prototype= Dog.prototype; // you think this completes the prototype inheritance, except that it directly points to the prototype chain, when you modify the subclass, the corresponding modification of the parent class. And since he's two points to a prototype, then you just use the dog to create it, and then you lose the meaning of inheritance.

Therefore, it is wrong to direct the prototype chain to the parent class, and here we can use an empty function as a relay to complete the inheritance of the prototype chain:

functionDog (name,age) { This. name=name;  This. age=Age ; Dog.prototype.eat=function() {alert ("Me this year" + This. age+ "Years old"); }}functionLittledog (name,age) { This. name=name;  This. age=Age ;}functionF () {}f.prototype=Dog.prototype; Littledog.prototype=NewF (); LittleDog.prototype.constructor=Littledog;varxiaogou=NewLittledog ("Wang Choi", 13); Xiaogou.eat ();//The method in the parent class is called by the puppy, and a pop-up box is returned, indicating that the inheritance succeeded.

This intermediate function is used to complete the inheritance of the class. It did not change the original dog's prototype chain, but also completed the inheritance, if you want to add a prototype method in Littedog, you can create a method and a property in New F (), of course, we can also encapsulate this inheritance method into a function, so that, The execution efficiency and aesthetics of our program are greatly improved:

1 function Inherits (child,parent) {2      var f = function () {}3      f.prototype = parent.prototype; 4      New f (); 5      child.prototype.constructor= child; 6 }// This is a wrapper function that can be applied with this function when inheriting from the class.

In the class inheritance, in addition to our above-mentioned prototype inheritance, as well as class inheritance, and class inheritance and prototype inheritance of mixing, then I will explain in the next chapter. This blog post is blogger self-creation, if reproduced please explain the source, thank you! In the next apprenticeship, if there is any mistake, please master correct, thank you!

Object inheritance relationships in JavaScript

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.