JS Learning summary----design Pattern

Source: Internet
Author: User
Tags gety hasownproperty

one, Single case mode

The role of the object data type

Put the properties and methods that describe the same thing (the same Object) in a memory space, play a role in grouping, so that the attributes between different things, even if the property name is the same, there is no conflict with each other

The pattern we put in this grouping code is called "singleton mode".

In Singleton mode, we call Person1 or person2 a "namespace."

        var = {            name:' Zhang San ', age            :person1        }var person2 =  {            name:"john doe", age                         :-

  Singleton mode is a pattern that is often used in project development because we can use a singleton pattern for our "modular development" in our Projects.

Modular development: for a relatively large project, requires a collaborative development of multiple people, we will generally be based on the requirements of the current project into a number of functional modules, everyone responsible for part, while developing, and finally the code of each person to Merge.

var utils = {            select:function() {            }        }        var searchrender = {change            :function() {                utils.select (); // calling the external method                 this . Clickeven ();            },            clickeven:function() {                            }        }

second, The factory model

Although the singleton mode solves the function of grouping, but does not realize the batch production, belongs to the manual operation mode, so the factory pattern Appears.

Put the code that implements the same thing into a function, and if you want to implement it again, you don't need to rewrite the code, just execute the current Function.

Low-coupling high cohesion: reduces redundant code in the page and improves code reuse

function Createjsperson (name,age) {            var obj = {};             = name;             = Age ;             function () {                console.log (' OK ')            }            return  obj;         var p1 = Createjsperson ("xiao wang", 12);

JS is a lightweight script "programming language" (HTML+CSS is not a programming language, it belongs to the markup Language)

all programming languages are inheritance, encapsulation, polymorphism of the class of object-oriented Development.

Inheritance: subclasses inherit properties and methods from the parent class

Polymorphism: multiple forms of the current method background Language: polymorphic contains overloads and overrides (overloaded: method names are the same, parameter types are Different)

There is no overload in js, the method name is the same, the back will cover the front, and finally only one

JS has an operation similar to overloading but not overloading: we can implement different functions depending on the parameters Passed.

function sum (num) {            if(typeof num = = = "undefined") {                return 0            }             return Num        }        SUM (+);        Sum ()

Overriding: subclasses overriding methods of parent class

third, the structural function mode

  The purpose of the constructor pattern is to create a custom class and create an instance of the class

The difference between a constructor pattern and a factory pattern:

1, the implementation of the time

normal function Execution->createjsperson ()

Constructor pattern->new Createjsperson () after new execution, our Createjsperson is a class, and the return value (p1) of the function execution is an instance of the Createjsperson () class.

2, when the function code execution

Same: both form a private scope, and then the formal parameter assignment-----------the code is executed from top to bottom (like the normal function, He also has a side of the Function)

Different: before the code executes, without having to create the Obj object manually, the browser defaults to creating a value for the object data type, which is actually an instance of our current class, followed by the code from top to bottom, with the current instance being the executing body (this represents the current instance). Then assign the property name and the attribute value to the current instance, respectively. The browser will return the created instance by Default.

function Createjsperson (name,age) {
The object that the browser creates by default is our instance, p1, this. Name = name; this. age = Age ; this function () { console.log (' OK ') } }
var p1 = new Createjsperson (' Zhang San ', 12);
var P2 = new Createjsperson (' John Doe ', 13);
    
var res = Createjsperson ("similar", 7);//this Write is not a constructor-mode execution but a normal function execution because there is no write return so res = undefined
And Createjsperson This method is the window

Create an Array:

var ary = [];//literal method

var ary = new Array ();//how The constructor mode executes,//instance creation

Either way, Ary is an instance of the array class.

Attention:

All of the classes in JS are function data types, which become a class through new execution, but it is also a normal function.

All instances in JS are object data types.

In constructor mode, the this.xxx = XXX in the class (in the function Body) is an instance of the current class

Although P1 and P2 are Createjsperson instances of this class, they all have writejs, but the methods between the different instances are not the Same.

The attribute added to an instance in a class (this.xxx = Xxx) belongs to the private property of the current instance, and the instance and instance are separate individuals, so private properties are not equal.

The extension code is as Follows:

functionFn () {varnum = 10;  this. x = 100;  this. GetX =function(){                //this-> need to see Getx execution.Console.log ( this. x)} }        varF1 =NewFn; varF2 =NewFn; F1.getx ();//This is f1->100        varSS =f1.getx; SS ()//this represents window->undefinedConsole.log (f1.num)//undefined        /*        1, in the constructor mode of the new Fn () execution, if FN does not need to pass parameters, the following parentheses can omit 2, this problem: in the class this.xxx = xxx is an instance of the current class, and a property value (method), the method of the This needs to see when the method executes, whether there is "." before you know this is who 3, the class has a common function of the side, when the function executes, var num is only the private scope of the current formation of private variables, it and our F1 this instance does not have any relationship,        Only this.xxx = xxx is equivalent to F1 this instance to add private properties and methods, and our F1 have a relationship ... 4, in the constructor mode, the browser will default to return our instance (return is a value of the object data type); if we have manually written return return: The value returned is a basic data type, the current instance is unchanged, for example: return 100. Our F1 or the current instance of FN Returns a value of a reference data type, and the current instance is replaced with the value returned by itself, for Example: Return{name: ' John Doe '} Our F1 is not an instance of fn, but the object {name: ' John Doe '} 5, Detecting A Whether an instance belongs to this class->instanceof console.log (f1 instanceof Fn)//true console.log (f1 instanceof Array)//fal            Se console.log (f1 instanceof object)//true Because all instances are object data types, and each object data type is an instance of the built-in class of objects, so F1 is also an instance of it        For the detection data type, typeof has its own limitations, can not subdivide objects under object, array, regular ... 6, F1 and F2 are all fn, an instance of this class, have X and GetX two properties, but these two properties are their own private properties, so: console.log (f1.getx===f2.getx);//false 7, in: Detecting whether a property is To this object attr in object, whether it is a private property or a public property, as long as it exists, use in to detectBoth are true Console.log (' GetX ' in f1)//true hasownproperty: used to detect whether a property is a "private" property of this object, this method can only detect private properties Console.log (f1.hasownproperty (' GetX '))//true
8. Isprototypeof: The function is used to indicate whether an object exists in the prototype chain of another Object. If present, returnstrue, or returnfalseThink: detects whether a property is the public property function Haspubproperty (obj,attr) {return (attr in Obj) &&!obj of the Object. hasOwnProperty (attr)}*/

four, prototype chain mode

The concept of classes and instances is possessed in the constructor pattern, and instance recognition is independent of each other between instances and instances

The prototype pattern based on the constructor pattern solves the problem of the method or property public, which extracts the same attribute and method from the instance into the public property and method, and wants to let the public put it on the Createjsperson.prototype.

1. Each function data type (normal function, Class) has a natural property: prototype (prototype), and this property is the value of an object data type

2, and on the prototype browser was born to add a property constructor (constructor), the property value is the current function (class) itself

3, Each object data type (normal object, instance, prototype ... ) is also born with a property: __proto__ (two underscore), The property value is the prototype of the class to which the current instance belongs (prototype )

function Fn () {            this. x = 100
This.sum = function () {
}
} function() { console.log (this. x); } Fn.prototype.sum = function () {} varnew Fn; var New Fn; Console.log (Fn.prototype.constructor===fn)// true

The following diagram to understand these three words

Attention:

object is the base class for all object data types in JS (topmost class)

1, F1 instanceof Object->true because F1 through the __proto__ can be found to the superior, regardless of how many levels, finally always find an object

2, There is no __proto__ this attribute on Object.prototype

3. Prototype chain mode

F1.hasownproperty (' x ');//->hasownproperty is a property of F1

But we find that there is no such method on the private property of f1, how to deal with it?

When you get the value of a property by its name, it is first found on the Object's private property, and if this property exists in the private, it gets a private property Value. If the private is not, the prototype of the owning class is found by __proto__ (the properties and methods defined on the prototype of the class are the public properties and methods of the current instance), if the prototype is present, the Public property value is obtained, and if there is no prototype, the __proto__ on the prototype is Continued. Continue to look up, always find object.prototype so far ...

The mechanism for this lookup is our "prototype chain pattern".

F1.getx = = = F2.getx->true

F1.__proto__.getx ===f2.getx->true

F1.getx = = = Fn.prototype.getX true

    F1.sum = = = F2.__proto__.sum->false

F1.sum = = = Fn.prototype.sum->false

In the IE browser, our prototype mode is the same principle, but IE browser afraid you through the __proto__ to change the public, prohibit us to use __proto__

Extension code:

/*in prototype mode, This is commonly used in two cases in a class this.xxx = xxx;this-> The instance of the current class in a method this-> look at the time of execution "." Who's in front of this? 1, you need to determine the direction of this (who this is) 2, replace this with the corresponding code 3, follow the prototype chain to find the results*/        functionFn () { this. x = 100;  this. y = 200;  this. GetY =function() {console.log ( this. y)} } Fn.prototype={constructor:fn, y:300, GetX:function() {console.log ( this. x)}, getY:function() {console.log ( this. y)} }        varf =NewFn f.getx ();// -F.__proto__.getx ();//undefined console.log (f.__proto__.x)        //extend our approach on the prototype of the built-in Class: array de-weightArray.prototype.myUnique =function(){            //this->ary            varobj = {}             for(vari = 0;i< this. length;i++){                varCur = this[i]; if(obj[cur] = =Cur) {                     this[i] = this[ this. length-1];  this. length--; Continue} obj[cur]=cur; } obj=NULL; return  this;//purpose in order to realize the Chain-style notation        }        //chained notation: Executing a method that completes an array can be followed by the next method        //principle: ary Why you can use the sort method: because sort is the public method on array.prototype, and the array ary is an instance of array, ary can use the sort method, Array to use the properties and methods defined on our array prototype.         //The return value of the sort execution completion is a sorted "array" that can be executed reverse        //the return value of reverse execution completion is a sorted "array" that can perform pop        //the return value of the pop execution completion is the deleted data, not an array.Ary.sort (function(a, B) {returnAb; }). Reverse (). pop ();

  Extended-bulk Set public properties 

//1, from an alias        functionFn () { this. x = 100; }        varPro = fn.prototype;//assign the original prototype address to pro, and now they're working on the same memory spacePro.getx =function() {} pro.gety=function() {} Pro.getz=function(){                    }        //2, reconstruct the prototype object of the method, and his own new to open up a heap of memory, store our public properties and methods, the browser was originally opened to the Fn.prototype to replace the        functionFn () { this. x = 100; } Fn.prototype={constructor:fn, A:function() {}, B:function(){            }        }        varf =NewFn ()//1, only the browser is born to Fn.prototype open heap memory inside only constructor, and we ourselves open this heap memory does not have this property, so constructor point is not FN but objectConsole.log (f.constructor)//before I did anything.        //in order to be consistent with the original, we need to manually increase the point of constructor        //2. Add public properties to the built-in class in this way        //adding array weight to the built-in class arrayArray.prototype.unique =function() {} Array.prototype={constructor:array, unique:function() {}} Console.log (array.prototype); //This way we will replace the properties and methods that were already present in the prototype, so if we modify the built-in class in this way, the browser will give the masked        //But we can modify the built-in method one by one, when we add the method to the prototype of the array in the following way, if the method name and the original built-in repetition, will be built-in changes to the built-in class after the prototype of the addition method, naming all need to add a special prefixArray.prototype.sort =function() {console.log (' OK ')        }

JS Learning summary----design Pattern

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.