Read Catalogue
- Begin
- Prototype
- Prototype chain
- Inherited
- Closed Package
- Use of closures
Back to Top
prototypes
At the beginning I don't want to straightforward to introduce you to what is a prototype, because it does not allow you to enjoy the thrill of the prototype, we start from the "original Dream" talk about
Create an object in JS we initially created it directly, and then we had the factory model , and the code was roughly the following:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title>Factory mode Creation Object</title> <Scripttype= "Text/javascript" >//----------Create objects directly-------------varper =NewObject (); Per.name ="Piziyimao"; Per.say =function() {Alert ( This. name); }//Each time this creates a "class" object, how troublesome Ah!? There's wood with a constructor, wow?! So there is a variant of the factory model//-----------"Factory mode"--------------functionCreateper (name) {varper =NewObject (); Per.name = name; Per.say =function() {Alert ( This. name); }returnPer }varP1 = Createper ("Pizi");varP2 = Createper ("Yimao"); Alert (P1.say = = P2.say);//false</Script></Head><Body></Body></HTML>
But there are three drawbacks to the factory model
1, each creation of a type of object to write a separate construction method
2, the same constructor Createper generated two objects do not share the instance, consumes memory resources P1.say = = P2.say return false is proof
3. Constructor Createper defines the cost of the closure when anonymous functions are running "do not understand, see the end of the article closure"
Use the constructor pattern to solve the first problem
Define a person "class", which assigns values internally through this point, and then creates the object in the way of new person
Roughly as follows:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" > FunctionPerson (name,age) { This. name = name; This. Say =function() {Alert ( This. name); } }varP1 =NewPerson"Pizi");varP2 =NewPerson"Yimao"); P1.say ();</Script></Head><Body></Body></HTML>On the 23rd issue, we need to use prototypes to solve
Q: What is a prototype?
A: Each function has a prototype property, which is an object. It allows all object instances to share the properties and methods it contains.
The following uses prototypes and constructors to produce objects together
The code is as follows:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" > FunctionPerson () {} Person.prototype.name ="Pizi"; Person.prototype.say =function() {Alert ( This. name); }varP1 =NewPerson ();varP2 =NewPerson (); P2.name ="Yimao"; Alert (P1.say = = P2.say);//true</Script></Head><Body></Body></HTML>
However, it is not a good idea to create a property within a constructor, "as in the code above, name can be declared directly in the constructor," but both have a suitable range.
Q: How are prototypes and constructors selected?
A: When a member in A constructor generates a closure, try to define it as a prototype, which reduces overhead.
Try to define a general member, especially an object or an array, within a constructor, because a member defined by a prototype is shared by multiple instances
Back to the top of the prototype chain
There are two special objects in JavaScript: Object and function, which are constructors that are used to generate objects.
Object.prototype is the ancestor of all objects,
Function.prototype is the prototype of all functions, including constructors.
Objects in JavaScript are usually divided into three categories,
A class is a user-created object--an object that is explicitly constructed with the new statement in the general sense
A class is a constructor object--a function that generates a normal object through a new call
A class is a prototype object--specifically, the object that the constructor prototype property points to
Each of these three types of objects has a __proto__ property that points to the prototype of the object, which can be traced back to the Object.prototype from any object along which it begins to traverse.
The constructor object has the prototype property, which points to a prototype object that, when created with the constructor, will point to the prototype property of the constructor when the object is created by the __proto__ property.
The prototype object has the constructor property, which points to its corresponding constructor.
Code Demo:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" > FunctionF () {} Object.prototype.name =' OBJ '; F.prototype.name =' Piziyimao ';varobj =NewObject ();varf =NewF (); alert (f.name);//Display Piziyimao//f.__proto__ equivalent to Falert (f.__proto__.name);//Display Piziyimaoalert (f.__proto__.constructor.name);//f is equivalent to alert (f.constructor.name); alert (f.__proto__.constructor.prototype.name);//Display PiziyimaoAlert (F.__proto__.constructor.prototype = = f.__proto__);//truealert (obj.name);//Display OBJalert (f.__proto__.__proto__.name);//Display OBJalert (f.__proto__.__proto__==obj.__proto__);//Display True</Script></Head><Body></Body></HTML>
Defines a constructor called F () and produces an object F. Adding prototype objects to object and F, respectively
The intricate relationship between them
Basic calculation is a prototype chain. inheritance is achieved by the mechanism of the prototype chain . "The essence of inheritance is that an object can access the properties or methods of any prototype object on its prototype chain." 】
For example
The F object of the previous example, which has a shallow copy of all the properties of F.prototype and Object.prototype (copying only the base data type, not copying the object). So you can access f.constructor,f.tostring directly
Back to Top
InheritanceRealization of inheritance based on the thought of the prototype chain
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" >//--------------beta version------------------------functionA (name) { This. name = name; } A.prototype.say =function() {Alert ( This. name); }functionB () {//Modify a context object to implement the inheritance of a property by using apply ()A.apply ( This, ["a dime."]); } B.prototype.say = A.prototype.say;//Inheritance of implementation methodsvarb =NewB (); B.say ();//seemingly implemented, but this is not ideal, if a prototype more than say a method? ,///For example, another Play, it is not to manually add a corresponding method for B: B.prototype.play = A.prototype.play; Can we point the B prototype pointer directly to the A prototype address B.prototype=a.prototype; The answer is yes, but it will create a new problem//--------------upgrade------------------------ B.prototype = A.prototype;//Inheritance of implementation methodsvarb =NewB (); B.say ();//Ruffian a hair//look "calm", the real "undercurrent surging"B.prototype.play =function() {Alert ("I modified the A prototype method Oh!! Do you believe it or not? " ); }varA =NewA (); A.play ();//"I modified the A prototype method Oh!! Do you believe it or not? "If you say this does not violate the inheritance!" Then I'll never believe in love again.//q: Whose fault is this? A:A's fault, b just want to inherit the properties and methods of a, and a is "throw in the arms with the body"//--------------flagship version------------------------functionA (name) { This. name = name; } A.prototype.say =function() {Alert ( This. name); }functionB () {} B.prototype.play =function() {Alert ("Lennon molested me?! " ); }varb =NewA"a dime.");//By new to a class A object assigned to the B object, that can easily make money, not "wet" body, not the average person can think outB.say ();//var A = new A (); A.play ();//Error A object is not accessible</Script></Head><Body></Body></HTML>The diagram is as follows: Object and function are not drawn, bold lines for the inheritance method say () Call chain back to the top
Closed Package
closures : Intrinsic functions can be accessed to external functions/intrinsics that contain pointers to external functions
It is easier to understand closures on the basis of understanding the scope of the previous chapter
There are three drawbacks to the factory pattern production object in the prototype above, where a third shortcoming is adopted to understand the closure
The Factory mode code is simplified as follows:
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" >The //createper (name) method returns an anonymous functionfunctionCreateper (name) {return function() {alert (name); }} createper ("Piziyimao")();//piziyimao Result Description: Anonymous functions can be accessed inside the external function name//supplement:varb = Createper ("Piziyimao"); b ();varc = Createper ("a dime."); C ();//Ruffian a hair B and C do not affect each other, indicating that two closure instances have been generated, internally referenced by the name variables belong to their respective operating environment</Script></Head><Body></Body></HTML>Back to Top
use of closures
The above diagram illustrates the dangers of using closures, but I haven't told you what to do with closures.
The main uses of closures are two: 1. Implement nested callback Functions 2. Implementing a Private Member "JS object is not a private property"
Example of a callback function code:
<Scripttype= "Text/javascript" > FunctionGetpicbypost () {varXHR = CREATEXHR (); Xhr.open ("POST","Getpic.ashx",true); Xhr.setrequestheader ("Content-type","application/x-www-form-urlencoded"); Xhr.onreadystatechange =function() {//onreadystatechange callback functionif(Xhr.readystate = = 4) {if(Xhr.status = = 200) {varres = Xhr.responsetext; Alert"res="+ res); }Else{Alert ("Sorry, server Error"); }}} xhr.send ("Txtname=piziyimao"); }</Script>Private Member Example
<HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head> <title></title> <Scripttype= "Text/javascript" > varAddtimes =function() {varCount = 0;return function() {count++;returnCount } }varTest = Addtimes (); Alert (test ());//1 only call test to access the count variable inside the closure, don't be paranoid about "brute force" hahaAlert (test ());//2Alert (test ());//3</Script></Head><Body></Body></HTML>
You can not know the JS three