JavaScript design mode (i)

Source: Internet
Author: User

What is design mode? It means that for similar problems, we can use the same ideas and methods to solve them, and this universal thought and method is the design Pattern. Learning Design patterns can help us to quickly search for a clear idea when we encounter problems.

The first part: object-oriented JavaScript 1. JavaScript is a dynamic type Language.

A statically typed language forces the procedure to define the type of a variable when it is Used. The dynamic type language, when the program is running, has a type and does not need to be strictly defined. obviously, static type language requirements are stricter, but dynamic type languages cannot guarantee the type of Variables.  JavaScript is such a dynamic type language , and the advantage is that we can spend more time focusing on logic, rather than on the definition of variables, the code will be more Concise. Static and dynamic, We can understand the variable type of static and dynamic .

  

2. interface-oriented Programming and Duck model

The JavaScript Kingdom needed 100 ducks to form the choir, but only 99 were found, and just as a chicken was called a quack, we brought the chickens closer to the duck Choir. This means that we focus only on the behavior of the object, not on the object itself.

  Based on this idea, for example, if an object has a push and pop method, it can be used as a stack, and so on, the idea of programming is interface-oriented Programming.

  

  3. polymorphic

  The actual meaning of the polymorphism is that the same operation acts on different objects, which can produce different interpretations and different execution results. As shown below:

 var  makesound = function (animal) { Span style= "color: #0000ff;" >if   (animal instanceof Duck) {console.log ( "   quack  "      );  if   (animal instanceof Chicken) {con Sole.log (   giggle   " ); }}  var  Duck = function () {};  var  Chicken = function () {};makesound (new Duck ()); makesound (new Chicken ());  

You can see that the MakeSound function has different outputs for different inputs, which is polymorphic .

But what if we add another dog? Not only do we want to create a Dog's constructor, but also change the MakeSound function, that is, the extensibility is very bad.

  Solution: The most important idea behind polymorphism is to separate "what to do" from "who to do and how to do", that is, to separate unchanging things from mutable things.

  As shown Below:

varMakeSound =function (animal) {animal.sound ();//do what}varDuck = function () {};//Who's going to doDuck.prototype.sound =function () {console.log ("Quack Gaga");//What to do};varChicken =function () {}; Chicken.prototype.sound=function () {console.log ("cluck, huh ?");};varDog =function () {};D og.prototype.sound=function () {console.log ("Wang Woo");}; MakeSound (NewDuck ()); MakeSound (NewChicken ());

It can be seen that the invariant part of the above example is Animal.sound (), which we separate (to do). And then who to do, how to separate out, so that the scalability of the function is very good.

4. Encapsulation

The idea of encapsulation is to hide the internal implementation, improve the reusability of code, package changes .

  

5. Prototype Mode

In a class-centric object-oriented language, the relationship between classes and objects can be imagined as a relationship between a mold and a casting, and objects are always created from the class.

But in the idea of prototype programming, a class is not necessary, and an object may not have to be created from a class, and one object is obtained by cloning another Object.

Part Ii: this, call, apply

I've covered the use of this in more detail in the beauty of JavaScript Function. There are still some points to be mentioned Here.

We know that thisalways points to an object, perhaps a window object, perhaps an object that invokes the method it is in, or a newly created object that executes dynamically when the execution environment of the function is run, not when the function is Declared.

  Case One: as a method call to an object, this is the object that this is pointing to.

Scenario Two: as a normal function call, rather than an object method, this is the global object window.

Scenario Three: The constructor is called, then it points to the newly created Function.

Scenario Four: Function.prototype.call or Function.prototype.apply Call.

  

Note: in an object, if there is a callback function, we also want this to exist, what should I do?

You can assign this to that in the context of the object, and then use that, and there is the right Point.

Note the second: during the constructor invocation, if the object is returned at the end, this will point to the returned Object. As follows:

var MyClass = function () {    this"zzw";     return {        "htt"    };} var New  //  htt

If the constructor does not return an object, then the final result must be zzw, but if the object is returned, this must be the object Returned.

Note Three: The Docuemnt.getelementbyid () method needs to use This.

        var getId = function (id) {            return  document.getElementById (id);        }        GetId ("div""red";

This allows us to successfully obtain an element with the ID Div. But:

        var getId = document.getelementbyid;        GetId ("div""red";

This will cause an Error.

  At this point, because GetID is used to refer to document.getElementById (), and then call getid, it becomes a normal function call, the internal this point to window instead of Document. (this is required for the internal implementation of many engine document.getElementById methods).

  

  In the JavaScript version of design mode, the call and apply methods are very common, the ability to skillfully apply these two methods is we really become a JavaScript programmer an important Step.

  Function.prototype.apply and Function.prototype.call are obviously called by a Function.

Where apply accepts two parameters, the first parameter specifies the pointer to the this object in the function body ( previously said, this always points to an object ), and the second parameter is a collection of right subscript, which can be an array or an array of classes. apply passes the elements in this collection as arguments to the called Function. Call also receives two parameters, similarly, the first parameter specifies the pointer to this object in the body of the function, and the second parameter is the parameter that the function needs to accept (no call and apply function to receive parameters!). )。 Examples are as Follows:

        varMyObject ={c: the        }; varAnotherobject ={c: the        }        varc =233; function Outputnum (a, B) {varc =Ten; Console.log ([a, b, this. c]); } function Outputnumsecond (a, b) {c=Ten; Console.log ([a, b, this. c]); } outputnum (1,2);//[1, 2, 233]Outputnum.apply (NULL, [1,2]);//[1, 2, 233]Outputnum.apply (window, [1,2]);//[1, 2, 233]Outputnum.call (NULL,1,2);//[1, 2, 233]Outputnum.call (window,1,2);//[1, 2, 233]Outputnum.apply (myObject, [1,2]);//[1, 2, $]Outputnum.apply (anotherobject, [1,2]);//[1, 2, +]Outputnumsecond.apply (NULL, [1,2]);//[1, 2, ten]

  If the first argument is null, then this will point to the default host object, which is window in the Browser. however, in strict mode, this is still null in the body of the Function.

  

  Common errors

    

JavaScript design mode (i)

Related Article

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.