Javascript Object-Oriented programming

Source: Internet
Author: User

the most primitive class and object declaration methods

The class declaration is as follows:

var Cat ='' }

If we want to declare an instance of the Cat class, the code looks like this:

  var // Create an empty object //  Assigns a value Cat1.color = "Yellow" according to the properties of the prototype object ;  var cat2 == "Er Mao"= "BLACK";

However, there are two notable drawbacks to this:

    1. If you generate more than a few instances, it's very cumbersome to write.
    2. Between examples and prototypes, there is no way to see what the connection is.
constructor mode Create object

In fact, the constructor is no different from the normal function, the only trick is to use the this variable internally, so that the instance can be generated by using the new operator on the constructor, and then the this variable is bound to the instance object.

So the code above can be written using constructors like this:

functionCat (Name,color) {//constructor Function       This. name=name;  This. color=color;  This. Type = "Cat animal";  This. Eat =function() {alert ("Eat mouse");}; }//declaring class instances    varCAT1 =NewCat ("Da Mao", "Yellow"); varCAT2 =NewCat ("Er Mao", "Black");//CAT1 and Cat2 automatically contain a constructor attribute that points to their constructors. Console.log (Cat1.constructor= = Cat);//trueConsole.log (Cat2.constructor = = Cat);//true//JavaScript also provides a instanceof operator that validates the relationship between a prototype object and an instance object. Console.log (CAT1instanceofCat);//trueConsole.log (CAT2instanceofCat);//true

Have you ever thought about the disadvantage of the constructor, that is the waste of resources. As shown in the code above, each object will have its own name and color property, which is understandable for attributes, but if it is a method, each object will have its own but to achieve the same function of the method, it is not a huge waste of resources?

you notice the code above " Cat1.constructor = = Cat "

Explain it: any one of the prototype objects has a constructor property that points to its constructor. Each instance also has a constructor property, which calls the prototype object's constructor property by default.

constructor binding, that is, call (apply) to change the parent object's this point to a child object,

prototype Mode

JavaScript specifies that each constructor has a prototype property that points to another object. All properties and methods of this object are inherited by an instance of the constructor. So we can put all the attributes in the constructor, and put all the methods on the prototype.

So the above code can be used as follows,

functionCat (Name,color) {//declaring classes       This. name = name;//all attributes are placed inside the constructor       This. color =color; }//all methods are placed on the prototype chain.Cat.prototype.type = "Cat Animal"; Cat.prototype.eat=function() {alert ("Eat mouse")}; varCAT1 =NewCat ("Da Mao", "Yellow"); varCAT2 =NewCat ("Er Mao", "Black"); Console.log (Cat1.eat= = Cat2.eat);//true this time different instances share the same method on the prototype chain

How to detect the relationship between objects and instances, there are three ways

// true  
// true
inch // true
the only difference between hasownproperty and in is that if the property that inherits from the prototype chain returns TRUE, the hasOwnProperty returns false.



The above is not just about declaring classes and instantiating classes, but how each class inherits.
Here are some of the following:
Constructor inheritance
Prototype Mode inheritance
Copy inheritance
Constructor Inheritance
  function  Animal () {// parent class this. Species = "Animal"; }      function Cat (name,color) {// subclass            animal.apply (this, arguments) ; //    This is the implementation of inheritance.  Use the call or Apply method to bind the parent object's constructor to the child object on this . Name =  name;   this. color = color; }            

prototype mode inheritance
  function  Animal () {// parent class this. Species = "Animal";    }      function Cat (name,color) {// sub-        class this. Name =  name;   this. color = color; }    new= Cat;        

The classic of prototype schema inheritance is to have the prototype of a subclass point to an instance of the parent class, because each prototype object will have a constuctor to point to its constructor, and the above "Cat.prototype = new Animal ();" This code makes the constructor attribute of the prototype point to the animal, we think this is not chaos, so just use the "Cat.prototype.constructor = Cat;" To fix

Let's think about what the disadvantage of the above code is that each subclass must declare an instance of the parent class, so that the start is not a waste of resources. So if we use prototype mode to inherit, we will use the following method.

functionExtend (Child, Parent) {varF =function(){};//declaring an empty objectF.prototype = Parent.prototype;//to point the prototype chain of an empty object to the prototype chain of the parent object The F class is actually equivalent to the parent classChild.prototype =NewF ();//The prototype of the child object is still an instance of the parent object. It's just an empty object. Save ResourcesChild.prototype.constructor = child;//Fix the prototype chainChild.uber = Parent.prototype;//To open a channel on a child object, you can call the parent object's method directly. This line here, just to achieve the completeness of inheritance, is purely an alternative nature}//use the following as shown belowExtend (Cat,animal);//Cat Inheritance Animal    varCAT1 =NewCat ("Da Mao", "Yellow");//instantiating an object

Copy Inheritance
  function    Extend (Child, Parent) {  var p = parent.prototype;     var c = child.prototype;    for (varin == p; }

Copy inheritance in some way similar to other languages such as the idea of C #, looping through the property and then assign a value to another object, it seems to be able to implement inheritance, but have you ever thought about the drawbacks of the above method, if the property is a reference type, it is not chaos, A property that modifies the reference type of an instance causes the value of the corresponding property of the other object to change, so that inheritance can only be said to be incomplete. So how do we achieve deep copy inheritance?

 function   Deepcopy (p, c) { var  c = C | |     {};  for  (var  i in   p) { if  (typeof  p[i] = = = ' object ' } {C[i]  = (P[i].constructor = = = Array)?  [] : {};      Deepcopy (P[i], c[i]);  else   {C[i]  = P[i];  }}  return   C; }

In fact, the jquery library is the use of deep copy inheritance, you can think of why, because copy inheritance is very suitable for passing parameters, you want to write jquery plug-ins, write some configuration parameters when the use is not as follows, combine to think will understand a bit

    = $.extend ({        ' Default Name ',        +,        true    }, options);

object () method inheritance
  function Object (o) {  function F () {}///temporarily declares a constructor to  point the prototype property of the constructor to the parent object, so that the child object is linked to the parent object,    It then generates an instance and returns the prototype property of the object, f.prototype = o;   returnnew  F (); }

Reference to Ruan Master's JavaScript Object-oriented Programming series

recently found Ruan Master's article is really worth a look, we have time to see, his literary talent is very good, "prose" and "views and feelings" category of articles are written very well. Really some small admire him, but rather than admire others than to do their own admire people .

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.