JavaScript Design patterns and development practices object-oriented

Source: Internet
Author: User
Tags variable scope

1 Dynamic Type language

The static type language compiles when the variable type is determined, and the variable type of the dynamic type language is given a value after the variable is assigned to the program when it is run.

The advantages of static language: First, the compiler can find the type mismatch error, second, if the program explicitly specify the data type, the compiler can also be optimized for these information programs, improve program execution speed.

The disadvantage of static languages: forcing programmers to write programs according to strong contracts and adding more code.

  

The advantage of dynamic languages: Fewer code is written, and programmers can focus on business logic.

The disadvantage of dynamic language: The type of the variable cannot be guaranteed, and the type-related error may be found when the program runs.

Dynamic types do not require type detection, we can try any method of fishing for any object, regardless of whether it was originally designed to own the method.

2 polymorphic

The actual meaning of polymorphism: agreeing to operate on different objects can produce different interpretations and different results. That is, sending the same message to different objects that give different feedback based on the message.

    varMakeSound =function(animal) {if(AnimalinstanceofDuck) {Console.log (' Quack ' ); }Else if(AnimalinstanceofChicken) {Console.log (' Giggle ' );    }    }; varDuck =function(){}; varChicken =function(){}; MakeSound (NewDuck ());//Quack GagaMakeSound (NewChicken ());//cluck, huh ?

This code shows polymorphism, but adding an animal requires changing the MakeSound function.

The idea of polymorphism is to separate unchanging things from mutable things. By isolating the invariant parts, the variable encapsulation, which gives us the ability to extend the program.

    //isolate the unchanging part, that is, the animal will make a cry .    varMakeSound =function(animal) {animal.sound ();        }; //The variable parts are individually encapsulated, polymorphism is actually the polymorphism of the object    varDuck =function(){}; Duck.prototype.sound=function() {Console.log (' Quack ' );    }; varChicken =function(){}; Chicken.prototype.sound=function() {Console.log (' Giggle ' );    }; MakeSound (NewDuck ());//Quack GagaMakeSound (NewChicken ());//cluck, huh ?    varDog =function(){}; Dog.prototype.sound=function() {Console.log (' Wang Woo ' );    }; MakeSound (NewDog ());//Wang Woo

The most fundamental function of polymorphism is to eliminate conditional clauses by transforming the process-based conditional branch into the polymorphism of the object. The advantage of object-oriented design is that the behavior is distributed among objects and the objects are responsible for their own behavior.

    var googlemap = {        function() {            ' start rendering Google Maps ' );        }    };     var baidumap = {        function() {            ' start rendering Baidu map ' );        }    };
//   using conditional clauses    var function (type) {        if (type = = = ' Google ' ) {            googlemap.show ();        } Else if (Type = = = ' Baidu ' ) {            baidumap.show ();        }    };     // output: Start rendering Google Maps    // output: Start rendering Baidu map

    // using polymorphic    var function (map) {        ifinstanceof  Function) {            map.show ();        }    };     // output: Start rendering Google Maps    // output: Start rendering Baidu map

3 Package

The purpose of encapsulation is to hide information. Encapsulation includes encapsulated data, encapsulation implementations, package types, and package changes. Encapsulation is more than just hiding data, it also includes hiding implementation details, design details, and types of hidden objects.

Encapsulate data: JavaScript does not have public, private, protected, etc., can only use variable scope to implement encapsulation characteristics, can only simulate public and private.

Encapsulation implementation: Encapsulation makes the coupling between objects loosely, and the objects communicate only through exposed API interfaces. When you modify an object, it does not affect other functions of the program as long as the external interface does not change.

Package type: JavaScript has no support for abstract classes and interfaces.

Package change: "Design mode" summarizes 23 design patterns, which are divided into the creation of new models, structural patterns and behavioral patterns. Create a pattern, to create an object is an abstract behavior, the specific creation of what the object can be changed,

The purpose of the create pattern is to encapsulate the object's changes . Structured patterns encapsulate the direct combination of objects. Behavioral patterns encapsulate the behavior of objects.

4 prototype mode and prototype-based JavaScript object system

Some basic rules of prototype programming paradigm:

    • All the data are objects
    • To get an object, many by instantiating a class, instead finding an object as a prototype and cloning it
    • The object remembers its prototype.
    • If the object is unable to respond to a request, the request is delegated to its prototype

1 All the data are objects

The basic types of JavaScript include undefined, number, String, Boolean, object, function. In addition to Undefined,number, Boolean, and string, you can programmatically type the object by wrapping the class, and the root object of JavaScript is Object.prorotype.

2 to get an object, quite a few by instantiating the class, but finding an object as the prototype and the G function person (name) {

this. Name = name;    };     function () {        returnthis. name;    };     var New Person (' Sven ' )    //  output: Sven    //  output: Sven
ES5 in object.getprototypeof can see object // output: True

When a function is called with new, the function is a constructor that clones the Object.prototype object before doing anything else.

The process of understanding the new operation in browsers that expose object __proto__ properties, such as Chrome and Firefox

    varObjectfactory =function(){        varobj =NewObject (),//cloning an empty object from the Object.prototypeConstructor = [].shift.call (arguments);//gets the externally passed in constructor, this example is the personobj.__proto__ = Constructor.prototype;//point to the right prototype        varret = constructor.apply (obj, arguments);//to set properties for obj by borrowing an external incoming constructor        return typeofret = = = ' object '? Ret:obj;//ensure that the constructor always returns an object};

3 objects will remember its prototype.

The _proto_ property of an object by default points to its constructor's prototype object, which is constructor.prototype. It is precisely because the object is going to memorize its constructor's prototype through the __prototype__ property, and it is necessary to manually set the correct __proto__ point to the Obj object when impersonating new creates the object.

JavaScript Design patterns and development practices object-oriented

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.