Object Creation Method

Source: Internet
Author: User

1. Create an object through JSON

2. New object first, and then add attributes and Methods. Disadvantages: a large number of repeated codes will be generated.

var people = new OBject();people.name =  "aaaa";people.getName = function(){     alert('get the name:' +this.name);} 

3. Object literal. disadvantage: a large number of repeated codes are generated.

var people = {    name: "aaaa",    getName: function(){        alert('get the name:'+this.name);    }}

4. Factory mode. disadvantage: the object type cannot be identified.

function  createFunction(name){      var o = new Object();       o.name = name;       o.getName = function(){            alert('get the name: '+this.name);       }
return o;}

5. constructor mode. Disadvantages: Method sharing is not allowed.

function  People(name){     this.name = name;     this.getName = function(){          alert('get the name '+this.name);     }}

6. prototype mode. Disadvantages: Some attributes do not need to be shared.

var Peopel = {}People.prototype = {    constructor:People,    name:"aaa",    getName:function(){         alert('the name is:' +this.name);          }}

7. Combined use of the constructor mode and prototype mode

function People(name){    this.name = name;}People.prototype = {    constructor:People;    getName: function(){         alert('the name is'+this.name);    }}

8. Dynamic Prototype mode. This is a better object creation mode.

1 function People(name){2      this.name = name;3      if(typeof this.getName != "function"){4            People.prototype.getName = function(){5                  alert('the name is:' +this.name);6            }7      }8 }

 

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.