Another talk on JavaScript object-oriented programming

Source: Internet
Author: User



Preface: Although there is Chenhao "JavaScript Object-oriented programming" bead Jade in the front, but I can not help but also the superfluous to fill an article, mainly because of the language charm of JavaScript. In addition this article is an introductory article, I also began to learn JavaScript, have a little experience, just want to write an article, the article inevitably has the wrong place, but also please do not hesitate to spit.



Spit slot JavaScript



The first time you touch JavaScript, the language does make many regulars feel uncomfortable, and this discomfort comes from the brevity and rigor of JavaScript's syntax, which comes from the tragic name of JavaScript, I was thinking that Netscape's JavaScript designer was naming him that day must have been skull-flooded, so that JavaScript has been so many Bubaizhiyuan over the years, people think he is a Java appendage, a web toy language. That's why some people will disdain JavaScript and think that JavaScript is not a real language, but they are really wrong. JavaScript is not only a language, is a true language, and he is a milestone language, he created a variety of new programming model of the prototype inheritance, closures, the later dynamic language has a huge impact. As one of the most popular languages of the Day (none), look at the largest number of language types submitted on Git to understand. With the advent of HTML5, the browser will be on the PC, and there is a trend to replace the OS, JavaScript as a browser of the only true language, as the C-Unix/linux,java to the jvm,cobol of the mainframe , we also need to re-seriously understand and examine this language. In addition, the official name of JavaScript is: ECMAScript, this name is obviously much more handsome than JavaScript!



To the point, we cut into the subject--javascript of object-oriented programming. To talk about JavaScript's object-oriented programming, the first thing we need to do is forget about the object-oriented programming we've learned. Traditional C + + or Java object-oriented thinking to learn JavaScript object-oriented will bring you a lot of confusion, let us forget what we have learned, and start learning this special object-oriented programming. Since is OO programming, how to understand OO programming, remember to learn C + +, learned for a long time not to get started, and later had the privilege to read the "Inside the C + + Object Model" This masterpiece, suddenly enlightened, So this article will also explore the OO programming of JavaScript in the way of object model. Because of the specificity of the JavaScript object model, the inheritance of JavaScript is very different from traditional inheritance, and because there is no class in JavaScript, it means that there is no extends,implements in JavaScript. So how does JavaScript actually implement OO programming? All right, let's get started, go for a stroll in JavaScript's oo world.



First, we need to look at how JavaScript defines an object. Here is one of our object definitions:



var o = {};


You can also define an object like this


functionf() {
}


Yes, you're not mistaken, in JavaScript, functions are objects.


1 var array1= [ 1,2,3];


Of course I can.



An array is also an object.



For other descriptions of the basic concepts of objects, please refer to the Chenhao "Javascript Object-oriented Programming" article.



Objects have, the only thing is class, because there is no class keyword in JavaScript, and the existence of function,function so that we can work around the definition of the class, before extending the subject, We also need to understand the most important properties of a JavaScript object,__proto__ members.



__PROTO__ Members



Strictly speaking, this member should not call this name, __proto__ is the address in Firefox, __proto__ only in the Firefox browser can be accessed. As an object, when you access one of the members or methods, if this object does not have this method or member, then the JavaScript engine will access the object's __proto__ member to point to another object, and in that object to find the specified method or member, If it cannot be found, it will continue to be recursively searched through the object pointed to by the __proto__ member of that object until the list ends .



OK, let's give an example.



For example, the array object defined above array1. When we create a Array1 object, the object model Array1 actually in the JavaScript engine is as follows:






The Array1 object has a length property value of 3, but we can add elements to the array1 in the following ways:

array1.push(4);


Push This method comes from a method (Array.prototye.push ()) that the __proto__ member of the Array1 points to the object. It is because all array objects (created by []) contain a __PROTO__ member that points to the same method object (Array.prototype) as Push,reverse, so that these array objects can use methods such as Push,reverse.



So this __proto__ property is equivalent to the "has a" relationship in object-oriented, so long as we have a template object such as Array.prototype, and then point the other object __proto__ property to this object An inherited pattern has been completed. Not bad! We can do this completely. But don't be happy too early, this property is only valid in Firefox, other browsers have properties, but cannot be accessed through __proto__, only through the Getprototypeof method, and this property is read-only. It seems that it is not easy for us to implement inheritance in JavaScript.



Function Object prototype member



First, let's look at the definition of a function prototype member,



When the A function object is created, it's given a prototype member which is an object containing a constructor member which is a reference to the function object



When a function object is created, the function object has a prototype member, which is an object that contains a constructor child member that points to the function object.



For example:



functionBase() {
    this.id ="base"
}


Base This function object has a prototype member, about the constructor is actually the base function object itself, why do we call such a function constructor? The reason is that this type of function is designed to work with the new operator. In order to be different from normal function objects, the first letters of such functions are generally capitalized. The primary function of a constructor is to create a class of similar objects.



The above code in the JavaScript engine object model is like this





new operator


With the introduction of the underlying concept above, and with the new operator, we are able to create objects in the way that traditional object-oriented class + new is created, and in JavaScript we make this kind of a pseudoclassical.



Based on the above example, we execute the following code



var obj =new Base();


What is the result of this code, the object model we see in the JavaScript engine is:



What exactly did the new operator do? It's really simple, and it's done three things.



varobj  = {};
obj.__proto__ = Base.prototype;
Base.call(obj);


In the first line, we created an empty object, obj.



In the second line, we point the __proto__ member of this empty object to the base function object prototype member object



In the third line, we replace the this pointer of the base function object with obj and then call the base function, so we assign an ID member variable to the Obj object, the value of this member variable is "base", for the use of a call function, see Chenhao "Javascript Object-Oriented Programming article



What happens if we add some functions to the Base.prototype object?



For example, the following code:



functionDerive(id) {
    this.id = id;
}
Derive.prototype =newBase();
Derive.prototype.test =function(id){
    returnthis.id === id;
}
varnewObj =newDerive("derive");


So when we create a new object using new, the ToString method can also be accessed as a method of the new object, depending on the __proto__ feature. So we see:



Constructor, let's set the ' class ' member variable (for example, the ID in the example), construct the child object prototype, we'll set the public method of ' class '. Thus, the effects of class and class instantiation are simulated through function objects and JavaScript-specific __proto__ and prototype members and the new operator.
Pseudoclassical inheritance



We simulate the class, then how to do the inheritance? As a matter of fact, we simply point the prototype of the constructor to the parent class. For example, we design a derive class. As follows






What about the object model after this code is executed? According to the previous derivation, it should be the following object model






This way our newobj also inherits the ToString method of base class base and has its own member ID. about how this object model is deduced is left to your classmates, referring to the previous description, the derivation of this object model should not be difficult.



Pseudoclassical inheritance will let students learn c++/java slightly feel a little comfortable, especially the new keyword, see Durt kind, but although the two are similar, but the mechanism is completely different. Of course, what kind of inheritance can not be inseparable from the __proto__ members.



Prototypal inheritance



This is another way of inheriting JavaScript, this inheritance is the previous Chenhao article "Javascript Object-oriented programming" in the CREATE function, it is very unfortunate that this is the ECMAScript V5 standard, Support V5 browser currently appears to be IE9, The latest version of Chrome and Firefox. Although looking at a lot, but as a IE6 of the hardest hit China, I suggest you still avoid using the CREATE function. Fortunately, before the CREATE function, JavaScript users have designed the equivalent of this function. For example: Let's look at the object function of Douglas Crockford.



functionobject(old) {
   functionF() {};
   F.prototype = old;
   returnnewF();
}
varnewObj = object(oldObject);


For example, the following code snippet


varbase ={
  id:"base",
  toString:function(){
          returnthis.id;
  }
};
varderive = object(base);


The object model after the execution of the above function is:






How to form such an object model, the principle is very simple, as long as the object this function extension, you can draw this model, how to draw the reader himself to draw it.



Such inheritance is referred to as prototype inheritance. It is relatively easier to inherit than pseudoclassical. For this reason, ECMAScript V5 adds the CREATE function, allowing developers to quickly implement prototype inheritance.



Both of these inheritance methods are the most commonly used in JavaScript. With this tutorial, you should have some ' principle ' understanding of JavaScript oo programming.



Reference:



"Prototypes and inheritance in JavaScript prototypes and inheritance in JavaScript"
Advance Javascript (Douglas crockford video, be sure to see it)



Off Topic:



After web2.0, the Web application is rapid development, now in the HTML5 release, the browser function is greatly enhanced, I feel browser is far from a browser so simple. Remember that the father of C + + once said that Java,java is not a cross-platform, Java itself is a platform. Today's browser is itself a platform, fortunately this platform is based on standards. If browser is a platform, due to browser security sandbox restrictions, personal computer resources are used very little, feel browser is a NC (Network computer)? We're back at Sun's original idea, is sun too strong?






Another talk on JavaScript object-oriented programming


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.