Detailed analysis of four methods for creating objects in Javascript and four methods for creating objects in javascript

Source: Internet
Author: User

Detailed analysis of four methods for creating objects in Javascript and four methods for creating objects in javascript

Preface

There are many ways to create objects using Javascript. Now let's list the four methods, and list the advantages and disadvantages of each method, so that you can choose and use them. Let's take a look.

Factory Model

Function createPerson (name, age) {var obj = new Object (); obj. name = name; obj. age = age; return obj; // be sure to return, otherwise print undefined: undefined} var person1 = new createPerson ('Young ', 18); console. log (person1.name + ':' + person1.age );

Advantages:The factory mode solves the problem of creating multiple similar objects.

Disadvantages:The problem of object recognition is not solved (how to determine the type of an object)

Constructor Mode

 function Person(name,age){ this.name = name; this.age = age; } var person1 = new Person('Young',18); console.log(person1.name + ':' + person1.age);

Before talking about the advantages and disadvantages, let's talk about her own little story.

Use constructor as a function

Function Person (name, age) {this. name = name; this. age = age; this. sayName = function () {return this. name ;}// use var person1 = new Person ('Young ', 18) as the constructor; person1.sayName (); console. log (person1.name + ':' + person1.age); // call Person ('wind', 18) as a common function; console. log (window. sayName (); // call var obj = new Object (); Person in another scope. call (obj, 'bird ', 100); console. log (obj. sayName ());

Constructor advantages and disadvantages

Advantages:The instance can be identified as a specific type

Disadvantages:Each method must be re-created on each instance. You can also change it like this:

 function Person(name, age){ this.name = name; this.age = age; this.sayName = sayName; } function sayName(){ return this.name; }

Instead, the global function is called, so there is no encapsulation... The following prototype can make up for this deficiency.

Prototype

Function Person () {} Person. prototype. name = 'Young '; Person. prototype. age = 18; Person. prototype. sayName = function () {return this. name;} var person1 = new Person (); console. log (person1.sayName (); var person2 = new Person (); console. log (person1.sayName (); alert (person1.sayName === person2.sayName); // person1 and person2 access the same sayName () function of the same group of attributes.

Although the values stored in the prototype can be accessed through the object instance, the values in the prototype cannot be overwritten through the instance object.

 function Person(){  } Person.prototype.name='Young'; Person.prototype.age=18; Person.prototype.sayName=function(){ return this.name; }  var person1=new Person(); var person2=new Person(); person1.name='Wind';  console.log(person1.sayName());//Wind console.log(person2.sayName());//Young alert(person1.sayName==person2.sayName);//true

When we callperson1.sayNameThe parser first checks whether the instance person1 hassayNameYou can call your own properties. If not, you can search for properties in the prototype.

 function Person(){  } Person.prototype.name='Young'; Person.prototype.age=18; Person.prototype.sayName=function(){ return this.name; }  var person1=new Person(); var person2=new Person();  person1.name='Wind'; console.log(person1.sayName());//Wind console.log(person2.sayName());//Young  delete person1.name; console.log(person1.sayName());//Young console.log(person2.sayName());//Young

UsehasOwnPropertyTypeThe method can detect whether an attribute exists in the prototype or in the instance. The method inherits from the Object, and the value true in the instance and false in the prototype.

Instance attribute on the enumerated objectObject.keys()Method

 function Person(){  } Person.prototype.name='Young'; Person.prototype.age=18; Person.prototype.sayName=function(){ return this.name; }  var keys=Object.keys(Person.prototype); console.log(keys);//["name", "age", "sayName"]

Advantages and disadvantages of Prototype

Advantages:You do not need to reapply the request to each instance for each method.

Disadvantages:Few people use the prototype mode independently .. Problem details

 function Person(){  } Person.prototype={ constructor:Person, name:'Young', age:18, friends:['Big','Pig'], sayName:function(){ return this.name; } }; var p1=new Person(); var p2=new Person(); p1.friends.push('Mon'); console.log(p1.friends);//["Big", "Pig", "Mon"] console.log(p2.friends);//["Big", "Pig", "Mon"]

It is precisely because instances generally have their own attributes, and we put them herePerson.prototypeSo with the modification of p1, the entire instance, including the prototype, is modified. Then, we can combine the constructor mode and the prototype mode.

Constructor mode and prototype mode

 function Person(name,age){ this.name=name; this.age=age; this.friends=['Big','Pig']; } Person.prototype={ sayName:function(){ return this.name; } }; var p1=new Person('Young',18); var p2=new Person('Wind',78); p1.friends.push('Raganya'); console.log(p1.friends);//["Big", "Pig", "Raganya"] console.log(p2.friends);//["Big", "Pig"] console.log(p1.friends==p2.friends);//false console.log(p1.sayName==p2.sayName);//true

This mode is currently the most widely used and the most consistent method to create a custom type. Is a default mode used to define the reference type.

Summary

The above is all about the analysis of the method for creating objects in Javascript. This article summarizes the four methods and their advantages and disadvantages, hoping to help you learn how to use Javascript.

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.