On the creation of JS object and the understanding of 6 kinds of inheritance mode and the _javascript skill of reverie

Source: Internet
Author: User
Tags constructor inheritance

There are six kinds of inheritance modes in JS, including prototype chain, borrowed constructor, combinatorial inheritance, prototype inheritance parasitic inheritance and parasitic combined inheritance. In order to facilitate the understanding of memory, I daydream about a process, a simple description of the 6 model.

A long story, let's call it a name Nu wa made people.

Creating objects

Nu wa One of the pinch people (create objects), so too slow, so designed a machine (function), want to create what, tell him what the characteristics and functions of the person, the machine to make. This is the factory pattern (using the same interface to create objects, generating a lot of repetitive code, and creating a Function (stencil)).

But machine-building people are also more troublesome (digging, mud, pinching their eyes, pinching their noses ...). So the idea of encapsulation came, nose and eye something in advance to pinch, to transform the machine, tell the people who want to build what kind of eyes, nose, machine can be directly installed OK, such a machine is a constructor.

There is still a problem, if you want to let the pinch people can run, the machine to everyone to install a ' run ' function, so the process is too slow, there may be errors, find a third party bar (function method defined outside the constructor, global scope). Third party is responsible for me to put the pinch of the people are loaded on the running function, I put it on the machine to use, every time the province processing. OK, people can run, very convenient, but the problem has arisen, the people still need to ' jump ', ' go '. n a function, can not find n a third party, then the construction of the machine is meaningless. So nu wa (developer) early created prototype mode ... My WA.

Each function in the prototype pattern has a prototype attribute, which is a pointer to the prototype object. The prototype object contains properties and methods that allow all instances to be shared, and the prototype object has a constructor property that contains a pointer to the function where the prototype property resides.

Seemingly a bit around, from Nu wa This angle is good to understand: The Creator Nu wa empress also invented a variety of molds (prototype object), to begin to build: 1 to build a kind of people--> use is to build this kind of person's mold. After all, you can create everything, what kind of mold to use. All human-made machines (functions) have their own only one mold (the prototype object), and the machine has a label [prototype], pointing to the mold, which has the ability to paste the production mark of the [constructor] attribute, pointing to this machine, indicating that the machine is the mold production. So what kind of people to create, only need to change the mold. This is the advantage of the prototype object, convenient, fast.

The production process is as follows:

1 Build Machine A:function Jqa () {}; There is a prototype attribute pointing to the stencil (prototype object)

2 mould:jqa.prototype={

CONSTRUCTOR:JQA,//the equivalent of labeling, produced by a machine,

Name: ' Lily ',

Skin: ' White ',

Run:function () {

Alert (this.name+ ' run '); }

This mold is responsible for making the name Lili, Skin white, can run this kind of person.

3 Build One this type of person var person1=new jqa ();

Recreate a person of this type var person2=new jaA ();

Both Person1 and Person2 have a [[prototype]] property, which means that the template A is processed and points to a template

Very perfect, the problem comes again, so the person that produces is same, the face walks to come to five identical white skin slim beauty, then have five a wipe the same short and ugly, too terrible. So machine A at the same time with the template, but also according to the female instructions to make this type of people have different characteristics, such as: The Blue eyes, that fat point. This extra function combines constructors and prototype patterns with the constructor implementation---"

The production process is as follows:

Combines the constructor pattern with the prototype mode

function person (name,skill,country) {

  this.name=name;

  This.age=skill;

  This.country=country;

  this.member=["Liu Feng", "Liu Yan"];

} The machine can listen to commands

 

person.prototype={

  Constructor:person,

  sayname:function () {

    alert (this.name);

  }

You can also use the template

 var person1=new person (' Chao ', ' cavalry ', ' Shu ');

 var person2=new person (' Liu Bei ', ' humane ', ' Shu ');

At this time, Nu wa lazy to take care of the machine while taking care of the template, so directly put the template in the machine: Initialize the prototype object in the constructor---"Dynamic prototyping mode is more convenient

The production process is as follows:

function Person (name,skill,country) {

 this.name=name;  This.skill=skill;

  This.country=country;

 if (typeof This.saycountry!=undefined) {

  person.prototype.saycountry=function () {  alert (this.country) ;

   };

       }

       }

var friend=new person (' Zhang Fei ', ' roaring ', ' Shu ');

Friend.saycountry ();          

Any further questions? OK, providing a parasitic constructor pattern: An internal machine is added to the machine, the internal machine is responsible for production, and the person who produces it is supplied to the external machine, and the external machine provides such kind of person. (generally not used to it.) )

Inheritance (My understanding-_-)

Question: Nu wa to build another group of people B, this batch of people's template B made good, but want to let this group of people have previously made the characteristics of the group of people, how to do? Let these people filter the previous template A and put it in B to create OK so that the class ' B ' will inherit the character of ' A ' class. How to filter: parent Instance = Child Prototype Build b template, make a a out, this a must filter a template, so let B's template equals a OK, problem solving.

Parent function, machine A, Class a person. Its instance a has the [[Prototype]] property and the custom property

function Supertype () {

this.property=true;

}

Add Getsupervalue method to Supertype prototype object (stencil a)

supertype.prototype.getsupervalue=function () {return

This.property 

}

//child function, machine b,b class person. Constructor subtype, which has the [[Prototype]] property and the custom Subproperty property

function subtype () {

this.subproperty=false;

}

Inherited the Supertype (prototype chain)

subtype.prototype=new supertype ()//Machine B=a

//Add Subtype method to Getsubvalue prototype object (Mold B)

subtype.prototype.getsubvalue=function () {return

tis.subproperty;

} ;

var insatance=new subtype ();

Alert (Insatance.getsupervalue ()); True

problem: Reference type value will change because instance shared property is the same as problem in prototype mode

Solution: Classic Inheritance (borrow constructor): In fact, the mold a design to machine B, but it is not a template, machine B will give production B to add these a properties and methods, but can be artificially controlled, Nu WA also ordered the machine B according to the delivery of different orders to produce different B.

To call a superclass constructor inside a subclass constructor

is the equivalent of instantiating a property of a parent class into a subclass? Super () in Java is in doubt

function supertype () {

this.colors=[' red ', ' blue ', ' green '];
}

Function subtype () {

//Inherits Supertype

Supertype.call (this);

}

var insatance1=new subtype ();

Insatance1.colors.push (' black ');

alert (insatance1.colors);//' Red,blue,green,black '

 

var insatance2=new subtype ();

alert (insatance2.colors);//' Red,blue,green '

1 Passing Parameters:

Borrow a constructor parameter to pass parameters to a superclass constructor in a subtype construction parameter

function Supertype (name) {

  This.name=name

}

Function subtype () {

//Inherits Supertype, and also passes parameter

supertype.call (this, ' Zhao ');

Instance property

this.age=29;

var insatance=new subtype ();

alert (insatance.name); Zhao

alert (insatance.age);//29

To ensure that the Supertype constructor does not override the properties of the subtype, you can add the properties that should be defined in the subtype after the superclass constructor is called.

problem: waste of labor, in the machine to create a features and attributes, then a template is useless, equivalent to return to the factory model, have a lighter, but also to drill wood to take fire?

Solution: Combining Inheritance

Work overtime in the company do nothing, now rush to work, the story is not going to go on, the successor model before moving the record bar.

The prototype chain and the constructor technology are combined to implement the inheritance of the prototype properties and methods using the prototype chain, and the constructor is used to inherit the instance property. This enables the reuse of functions by defining a method on the prototype, with the ability to ensure that each instance has its own attributes

Prototype Inheritance: method can, instance property cannot inherit; Borrow constructor: Instance property can, method not. Together, perfect.

 function Supertype (name) {

this.name=name;

thi.colors=[' red ', ' blue ', ' green ';

}

supertype.prototype.sayname=function () {

alert (this.name);

};

 

Function subtype (name,age) {

//Inheritance Property

Supertype.call (this,name);

This.age=age

///Inheritance Method

 subtype.prototype=new supertype ();

 

 Subtype.prototype.sayage=function () {

 alert (this.age);

 

var instance1=new subtype (' Zhaoyun ');

Instance1.colors.push (' black ');

alert (instance1.colors); ' Red,blue,green,black '

instance1.sayname ();//zhaoyun

instance1.sayage ();//29

 

var insatance2= New subtype (' Zhuge '),

alert (INSTANCE2.COLRS); Red,blue,green '

instance22.sayname ();//Zhuge

instance2.sayage ();//25

The above is small set for everyone to talk about the creation of JS object and 6 kinds of inheritance mode of understanding and reverie all content, I hope that we support cloud Habitat Community ~

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.