JavaScript MVC design pattern (Constructor, module, and prototype) tutorial

Source: Internet
Author: User
Tags constructor inheritance

JavaScript Object-oriented

JavaScript is a language of no class, but can be modeled using functions, which involves design patterns. Patterns are proven reusable solutions that can be used to address common problems encountered in software design and are often used to create templates for reuse.

The common way for JavaScript impersonation classes is to define a JavaScript function, use this to define properties and methods, and then use the New keyword to create an object instance. Such as

The code is as follows Copy Code

function WebSite () {
This.name= "open source Window";
This.url= "Oseye.net";
This.getinfo=function () {
Return this.name+ ":" +this.url;
}
}

var wb=new webSite ();
Console.log (Wb.getinfo ());



Creating Objects

In JavaScript, two common methods for creating new objects are:

The code is as follows Copy Code

var newobject={};
var newobject=new Object ();



However, these two ways of creating only one empty object are of no use, but there are four ways to extend it:

The code is as follows Copy Code

var website={};
"Dot" syntax
Website.url= "Oseye.net";
Website.getinfo=function () {
return this.url;
}
Console.log (Website.getinfo ());
Console.log (Website.url);

Middle Bracket syntax
website["name"]= "open source Window";
Console.log (Website.name);
Console.log (website["name"]);

With Object.defineproperty
Object.defineproperty (webSite, "url", {
Value: "Oseye.net by DefineProperty",
Writable:true,
Enumerable:true,
Configurable:true
});
Console.log (Website.url);

Using Object.defineproperties
Object.defineproperties (website,{
"url": {
Value: "Oseye.net by Defineproperties",
Writable:true,
Enumerable:true,
Configurable:true
},
' Name ': {
Value: "Open source windows by Defineproperties",
Writable:true
}
});
Console.log (Website.url + website.name);



You can use Object.create to implement inheritance, such as:

var website={};
Website.url= "Oseye.net";
Create mywebsite inherit from website
var mywebsite=object.create (webSite);
Console.log (Mywebsite.url);

Constructor (builder) mode

In the classic object-oriented programming language, a constructor is a special method for initializing a newly created object when memory has been allocated to an object. Although JavaScript does not support the concept of classes, it does support special constructor functions that are used with objects, such as:

  code is as follows copy code

     function WebSite (name,url) {
    this.url=url;
    this.name=name;
    this.getinfo=function () {
    return this.url+ "-" +this.name;    
   }
   }
    
    var ws= New WebSite ("Open source Window", "oseye.net");
    Console.log (Ws.getinfo ());



Module (modular) mode

The module pattern is based on object literals, so you need to know the meaning of the object literal. In object literal notation, an object is described as a comma-delimited set of name/value pairs that contain braces ({}), and syntax errors are not required after the last name/value of the object. The syntax is as follows:

The code is as follows Copy Code

var newobject={
Variablekey:variablevalue,
Fucntionkey:function () {
//.....
}
};


Example:

  code is as follows copy code

     var website={
    URL: "oseye.net",
    getinfo:function () {
    return this.url;
   }   
   };
    Console.log (Website.getinfo ());


Prototype (prototype) mode

Each JavaScript object has a Prototype property, and you can add methods dynamically to the class using the Prototype property. To implement the effect of "inheritance" in JavaScript. In fact, the prototype property is a reference to an object called a prototype object that contains methods and properties shared by the instance of a function, that is, when a function is used as a constructor call (called using the new operator), the newly created object inherits the properties and methods from the prototype object.

Seeing the above description, the Novice must be foggy! Before we understand prototype, let's look at a couple of things that are common in object-oriented objects:

    Private variables, functions: Variables and functions defined within a function if the interface is not provided externally, the external will not be accessible to the That is, a private variable and a private function

  code is as follows copy code

         function WebSite () {
        url= Oseye.net ";
        var getinfo=function () {
        }
       };
       //cannot access variable URLs and function GetInfo outside the website object, they become private and can only be used within website.
       //Even if instances of function website still do not have access to these variables and functions, the exception prompts "undefined"
         Console.log (New WebSite (). GetInfo ());



Static variables, functions: When a function is defined, it is passed "." The properties and functions that are added to it are still accessible through the object itself, but their instances are not accessible, and such variables and functions are called static variables and static functions, and the students who have used Java and C # are well aware of the static meaning.

The code is as follows Copy Code

function WebSite () {};
Website.url= "Oseye.net";

Console.log (WebSite (). URL); Oseye.net
Console.log (New WebSite (). URL); Undefined



    instance variables, functions: In object-oriented programming, in addition to some library functions, we want to define attributes and methods at the same time as the object definition, which can be accessed after instantiation, and JavaScript is done through this

  code is as follows copy code

        function WebSite () {
         this.url= "Oseye.net";
        this.getinfo=function () {
         return this.url;   
       }   
       };
        
        console.log ( New WebSite (). URL); Oseye.net
        Console.log (New WebSite (). GetInfo ());//oseye.net



It looks good, but you look at it.

The code is as follows Copy Code

function WebSite () {
This.url= "Oseye.net";
This.getinfo=function () {
return this.url;
}
};

var ws=new webSite ();
Ws.url= "Test.oseye.net";
Ws.getinfo=function () {
Return "Override GetInfo";
}

Console.log (Ws.url); Test.oseye.net
Console.log (Ws.getinfo ()); Override GetInfo

var ws2=new webSite ();
Console.log (Ws2.url); Oseye.net
Console.log (Ws2.getinfo ()); Oseye.net



This leads to the conclusion that the properties and methods of each instance are a copy of the object's properties and methods. If an object has tens of thousands of power methods, then each instance should be such a copy, a little scary!! When prototype came into being,

Whenever a new function is created, a prototype property is created for the function based on a specific set of rules, and by default the prototype property obtains a constructor (constructor) property by default. This property is a pointer to the function of the prototype property, some around the ah, write code, the above image!

The code is as follows Copy Code
function person () {}




According to the figure above, you can see that the person object automatically obtains the Prototyp property, and prototype is also an object that automatically obtains a constructor property that points to the person object.

When a constructor is invoked to create an instance, an internal pointer (many browsers with the pointer name of __proto__) points to the prototype of the constructor, which exists between the instance and the prototype of the constructor. Rather than between the instance and the constructor.

The code is as follows Copy Code

function person (name) {
This.name=name;
}
Person.prototype.printname=function () {
alert (this.name);
}

var person1=new person (' Byron ');
var person2=new person (' Frank ');



The instance Person1 of person contains the Name property and automatically generates a __proto__ property that points to the prototype of the person who can access the Printname method defined within the prototype.



Write segment test to see Prototype properties, methods are able to share

  code is as follows copy code

    function person (name) {
    this.name= Name
   }
    
    person.prototype.share=[];
    
    person.prototype.printname=function () {
    alert (this.name);
    }
    
    var person1=new person (' Byron ');
  & nbsp var person2=new person (' Frank ');
    
    person1.share.push (1);
    Person2.share.push (2);
    Console.log (person2.share);//[1,2]



Sure In fact, when the code reads a property of an object, it performs a search, the target is a property of the given name, the search begins with the object instance, returns if it is found in the instance, and if not, finds prototype. If it is still not found, continue to recursively prototype the prototype object until it is found, returning an error if recursion to object is still not present. Similarly, if you define a property or function with the same name as prototype in the instance, the prototype property or function is overwritten.

Of course, prototype is not specifically defined for solving the above problems, but it solves the above problem. With this knowledge, you can build a scientific, reusable object, and if you want the properties or functions of an instance object to be defined in prototype, you can pass the instantiation parameter by using the constructor if you want the property or method that each instance has individually defined into this.

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.