Day 5: javascript inheritance

Source: Internet
Author: User
Document directory
  • 1. process. inherits () v. s SYS. inherits ()
  • Ii. Object-based
  • Iii. Category
  • Iv. Conclusion
  • Refer:

People were cheated by his simple appearance when they came into contact with JavaScript. However, all of a sudden, FP, Oo, and the front-end ran to the backend, so they were very busy. Once you encounter some obstacles, the Javascript is also very bad-tempered. How do you get it and modify it? It will not be angry, but it will be too confusing, you and I are angry. I really don't know if you are playing JavaScript or becoming Js ......

Many people have been "confused" by JS, and they are deeply upset that they intend to rebuild the evil Javascript. The first thing they grasp is prototypical inherit )". For "prototype inheritance" and "class inherit", the godfather of the Javascript industry, Yahoo! Ui architect Douglas crockford (D. c .) it is regarded as a school issue, just as the FP functional formula is compared with OO, OO has become the mainstream, but it is not equal to FP, so it is difficult to become a school argument, otherwise, the dual opposition is non-black and white.

For example, the picture on the right is D.C himself, the old man, as the saying goes, the old man knows the Road, huh, huh.

D.C mainly means that the academic discussion of prototype inheritance has always taken a place, and there are also a group of language ideas based on this prototype inheritance. However, today, people do not know or have little knowledge about the OO methodology of prototype inheritance. In essence, the influence of Java/C # is influenced, and the majority of people who are familiar with class inheritance are involved. Back to the issue of prototype inheritance, prototype inheritance certainly also has the advantages of prototype inheritance, which has advantages, otherwise it will not be able to stand by itself. What are the advantages? If you have time to ask about Google or D.C, let the younger brother say what D.C has already said. Whatever the case, Lucky D.C.
Although it is not easy for everyone to accept the prototype inheritance of JavaScript, the concept of classes has been widely applied to the public, deep-rooted, how can we change it? It's too revolutionary, so you and I will continue to transform the inheritance of JavaScript to conform to your own production experience and practice the application ......

With the development of JavaScript, there are already several methods or channels for inheriting classes. What is the inheritance of nodejs today? Let's take a look.

Node. js inheritance does not discard prototype inheritance. On the one hand, it also applies a lot of class inheritance. One Class inherits one class, and one class inherits one class ...... SYS. inherits () is the method that inherits any two classes. This method supports two function parameters: SYS. inherits (subfn, basefn); sunfn is a subclass, and basefn is a parent class.

1. process. inherits () v. s SYS. inherits ()

It is worth noting that the namespace to which the inheritance method belongs. Originally, inherits () exists on the process object and is changed to the Sys object. If you type the old process. inherits (...) method, nodejs will prompt you that this usage has been abandoned. Instead, use SYS. inherits, that is, in the source code:

...... <Br/> process. inherits = removed ("process. inherits () has moved to SYS. inherits."); <br/> ......

In the new version of nodejs, there are other API naming changes. inherits is only one of them. Apparently, the author of ry made his own changes to make such a decision. The new version is always better than the old version, but is there anyone else who suggested him to do it without knowing it :). However, in private judgment, the inheritance method should be defined at the core language level, at least in sys (system), which is more appropriate and more appropriate than the semantics of process. Otherwise, how can process have inherited functions? It's strange. However, in other words, sys must be require for use, while process is the default Global Object and does not need to be used.
Require can be accessed.

Let's talk about the inherits () method and its inherits (Oh, It's really boring ). No, many JS libraries have special inheritance methods, prototype. the extend of JS is purely a copy object. In the early days, jquery had not considered the so-called "inheritance". Fortunately, there was room for it. Later, the author John heap JavaScript inheritance to a level and even imitated Java's super () all statements are available to implement JavaScript inheritance based on class. John also wrote a blog post, especially this blog post, which benefited me a lot from curiosity and learned about shell removal.
JS method inheritance-of course, those are post-mentioned, but it cannot be mentioned that jquery's inheritance method is named "extend ()", besides, the Yui/extjs stream is almost the same. However, why is the inheritance method of nodejs called inherits? It intentionally or unintentionally adds the-s tense of the third person! The translation of inherits is also the meaning of "inheritance", with the intention of OO, but it seems that there is no extend to remember, you will know when you press the keyboard ......

After explaining some background, I just want to increase your interest in inheriting inherit, so that you can go deeper into the subject. Well, let's go to the topic. Now let's take a look at SYS. inherits source code (exports. inherits, lib/sys. js line 327th ):

/** <Br/> * inherit the prototype methods from one constructor into another. <br/> * the function. prototype. inherits from Lang. JS rewritten as a standalone <br/> * function (not on function. prototype ). note: if this file is to be loaded <br/> * During bootstrapping this function needs to be revritten using some native <br/> * functions as prototype setup using normal JavaScript does not work as <br/> * expected during bootstrapping (see mirror. JS in r114903 ). <br/> * @ Param {function} ctor constructor function which needs to inherit the <br/> * prototype <br/> * @ Param {function} superctor constructor function to inherit prototype from <br/> */<br/> exports. inherits = function (ctor, superctor) {<br/> ctor. super _ = superctor; <br/> ctor. prototype = object. create (superctor. prototype, {<br/> constructor: {<br/> value: ctor, <br/> enumerable: false <br/>}< br/> }); <br/> };

It seems that nodejs is a bit special, and its implementation is not the same as that of Yui and ext. But what makes the Inheritance Method Different? Based on the source code, it seems that the key lies in the object. Create () method. What is object. Create? To solve the problem, we can start with the understanding of Object-based inheritance and class-based inheritance.

Ii. Object-based

The first is object-based inheritance. The concept of object-based inheritance allows the absence of the concept of class. All objects are inherited from objects. I want to get a new sub-object from a parent object. For example, a rabbit can be directly inherited from an "animal" object. In JS:

// Define the parent object animal <br/> var animal = new object (); <br/> animal. age = new number (); <br/> animal. eat = function (food ){...} <br/> // define the sub-object Rabbit <br/> var rabbit = new object (); <br/> rabbit. _ PROTO _ = animal;

So here we will all say "What, what object", without "class ". An object is the original "object" and the parent object at the top layer. The ultimate object of any sub-object in Javascript is this object. "New object" means to call the new command to execute the object constructor. This is an empty object. Animal. age = new number (); this sentence is to assign an animal object to the attribute named age, whose type is number; animal. eat = function (food ){...} is to assign a name
The eat method is used as an animal object. Its parameter is food. In this way, the animal object has the age attribute and the method of eating eat to form a standard object.

Next, because the rabbit must conform to the object's meaning, declare an empty object and assign it to the rabbit variable. Like this sentence: var rabbit = new object (); then pay attention to the fact that rabbit. _ PROTO _ = animal; is the statement for establishing an inheritance relationship. _ PROTO _ is an attribute of any object (provided that it is run in the JS enginer of Firefox). That is to say, each object has the _ PROTO _ attribute. The point of change _ PROTO _ is to change the object prototype-that is, the "parent object" that we call. That's right. It's just a simple JavaScript inheritance.

However, there is a compatibility issue.So easy to use _ PROTO _ is only available in Firefox's Js engine, and other JS engines won't be accessible to programmers.. (THX toqinfanpeng) There are various reasons. In short, it cannot be used directly -- it cannot be used.

That is to say, _ PROTO _ is not recommended. Fortunately, we know that JavaScript, as a dynamic language, supports late binding, that is, allows users to add or delete any member on an object. In this way, we can create a new object by copying the object members, as shown in the following example:

// Define the parent object animal <br/> var animal = new object (); <br/> animal. age = new number (); <br/> animal. eat = function (food ){...} <br/> // define the sub-object Rabbit <br/> var rabbit = new object (); <br/> for (var I in animal) {<br/> rabbit [I] = animal [I]; <br/>}

Write a for statement to list all the members of an animal and copy them to an empty object such as rabbit. After the loop, the "inheritance" is achieved. Then, write for as a general apply () method, as follows:

Object. apply = function (superobject, sonobject) {<br/> for (var I in superobject) <br/> sonobject [I] = sonobject [I]; <br/>}

It should be noted that the above "Copy member idea" can be correct and run without errors, but do you notice that apply () is mainly a (...) {...} loop. When we think of a "loop statement", it is easy to think of problems such as time consumption and whether it will lead to a lethal loop. Therefore, we can see whether this for loop can be used, in short, we can avoid loops. -- The depth of the problem involves the question of code Elegance: the use of apply () is considered not elegant, especially when more and more apply () applications are used, the result is all over (...) {...}. Of course, the most direct solution to elegance is JavaScript.
The language can directly replace apply (). You can see that although it is such a small problem, it is worth correcting. It seems that the pursuit of perfection, perfection, and better is not a blank saying.

Therefore, ecmascript V5.0 (v3.1), that is, the new JavaScript version specifies the object. Create () method and provides a method for deriving sub-objects from the parent object. The new usage is as follows:

// Define the parent object animal <br/> var animal = new object (); <br/> animal. age = new number (); <br/> animal. eat = function (food ){...} <br/> var rabbit = object. create (animal );

Very intuitive, right ~ A create () operation has been completed ~ In fact, let's look back at the significance of _ PROTO _ encapsulation. The implementation method is provided here (except mozllia and V8). For more information, see v8natives. JS 694th rows ):

Object. create = function (PROTO) {<br/> var OBJ = new object (); <br/> obj. _ PROTO _ = proto; </P> <p> return OBJ; <br/> };

Of course, the for method is also equivalent,

Object. create = function (PROTO) {<br/> var OBJ = new object (); <br/> for (var I In proto) <br/> OBJ [I] = proto [I]; </P> <p> return OBJ; <br/> };

If you want to take a shortcut and simply change es3.1 to object. Create (), you can only say "A shortcut ". In fact, there is other content behind it (some processes, some parameters ...... Some principles), but it does not affect the meaning of the trunk. If you can understand this, it will be good. You can leave a chance to explore other content, which saves me the trouble. (The constructor is highlighted in the second parameter ).

Here we have completed the inheritance of the first faction "Object-based. I think the "Object-based inheritance" statement is redundant, because the object is like a box and everything can be installed in. Inheritance does not mean anything except for object services !? Therefore, the object-based statement can be said that object-based statements are provided only when other ideas with higher intelligence are opposite.

Here, we can understand what prototypical inherit is like. The principle of process. inherits is probably out of breath after the mystery of object. Create () is uncovered.

Iii. Category

I sold a secret in the previous article. The more advanced "thoughts" are class! On the surface, classes are actually no different from objects. They also have methods, attributes, events, and other concepts. In fact, classes are Object Templates. Well, after clarifying this, we know that "class" is not born out of thin air as a special "thing. The following JS statement results are the same. We can compare the two to understand the process from "object" to "Class Object:

// Define a JS class (the class is represented as a function in JS) <br/> function Foo () {<br/> //...... Constructor Process <br/>}< br/> var o = new object (); <br/> O. constructor = Foo; <br/> Foo. call (o); // <--- this step is to call Foo (). More specifically, it is to call the foo constructor. The function is equivalent to VaR o = new Foo ();

Why call? Because the new command calls the constructor function Foo () {}, it will inevitably return the current instance object of this, namely:

Funtion Foo () {<br/> //...... Constructor Process <br/> // return this; <br/>}

What is the current instance object? -- In this example, It is O. O. In this way, we can see the "Sublimation" of the object to the class "!

Do you still think it is not thorough enough? We haven't finished it yet ~ We can combine the rabbit examples, also animals and rabbits, to write classes, thus giving birth to a kind of writing in Javascript!

Animal = function () {}< br/> animal. prototype. age = new number (); <br/> animal. prototype. eat = function (food) {<br/>}< br/> rabbit = function () {}< br/> rabbit. prototype = new animal ();

Just kidding. This is the way Javascript is written. The above statement completely removes the need for an object to define a hierarchy. Simply put, the meaning is to use the prototype of the function and add a function layer to determine what the parent object is. First of all, we can add "Constructor" compared to "Object-based" inheritance. For example, animial = function () {} and rabbit = function () {} is the constructor of the parent class and the constructor of the subclass. However, if I do not need a subclass constructor, it is impossible to write a function.
Function can have the prototype attribute to define members. Didn't we say that _ PROTO _ is an attribute not open? Only function _ PROTO _ is always open, that is to say, function objects all have the function of _ PROTO _: Apply () and call, but the name of _ PROTO _ becomes "No underline", that is, the function. prototype. In JS, templates for defining objects with functions are frequently written. A new class is to create an object and also enables prototype to play the role of defining the inheritance chain.

Since function. prototype is always open, can we use it instead of _ PROTO? Yes, just use an empty constructor. The original object. Create can also be written as follows:

Object. create = function (o) {<br/> function f () {}< br/> F. prototype = O; <br/> return new F (); <br/>}

Of course, this object method returns to the "Object-based inheritance" method. We can see from the methods introduced by D.C that these origins are traceable with the help of networks. For more information, see http://javascript.crockford.com/prototypal.html. In fact, object. Create should come from the D.C method. It seems that he is also a powerful promoter and does not know ...... Finally, I copied multiple Extend Codes to help me understand them. There is no difference in the principle. The key lies in simplicity and clarity.

Extend = function (Klass, zuper) {<br/> Klass. prototype = object. create (zuper. prototype); <br/> Klass. prototype. constructor = Klass; <br/>}

Iv. Conclusion

What I said today can be divided into the last two parts. The first part is intended to be inherited from nodejs. Although I don't know if there is much nonsense, the second part is not well connected, but I still said my words in the bottom of my heart. It is a few things to come and go, because they are highly abstract and may not be easy to clarify. It is not easy to say the circle as much as possible. He has the opportunity to correct the article on a daily basis, please read this article as a draft. If you have any doubts, please make sure you have an ax. If you have any tips, please give me a try!

Refer:
  • Http://ejohn.org/blog/ecmascript-5-objects-and-properties/
  • Http://javascript.crockford.com/prototypal.html
  • Use the super keyword in Ext. Extend ()
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.