Seven Ways JavaScript creates objects

Source: Internet
Author: User

Goto: Xxxgitone.github.io/2017/06/10/javascript Seven Ways to create objects/

There are many ways that JavaScript creates objects, and you can create individual objects by using the object constructor or the literal of the objects, obviously both of which produce a lot of duplicate code and are not suitable for mass production. The next step is to introduce seven very classic ways to create objects that have their pros and cons.

Factory mode

1 function Createperson (name, job) {2 var o = new Object ()3 o.name = name4 o.job = Job5 o.sayname = function () {6 Console.log (this.name)7   }8 return o9 }Ten var person1 = Createperson (' Jiang ', ' student ') Onevar person2 = Createperson (' X ', ' Doctor ')

This factory function can be called countless times, and each time it returns an object containing two attributes and a method.

Although the factory model solves the problem of creating multiple similar objects, it does not solve the object recognition problem, that is, you cannot know the type of an object

Constructor mode

1 function person (name, job) {2  this.name = name3  this.job = Job 4   this.sayname = function () {5    console.log (this.name)6   } 7 }8var person1 = new Person (' Jiang ', ' student ')9 var person2 = new Person (' X ' , ' Doctor ')

There are no created objects displayed, use new to invoke this constructor, and use new to do the following automatically

    • Create a new object

    • This new object will be executed [[prototype]] Link

    • This new object is bound to the this of the function call

    • Return this object

Use this method to create objects to detect object types

1 person1 instanceof Object//True 2 person1 instanceof person//true

But using constructors to create objects, each method is re-created on each instance

Prototype mode

1 function Person () {2} 3 Person.prototype.name = ' Jiang ' 4 Person.prototype.job = ' Student ' 5 Person.prototype.sayName = function () {6  console.log (this.name)7 }8 var person1 = new Person ()

Add information directly to the prototype object. The advantage of using prototypes is that you can have all of your instance objects share the properties and methods that it contains without having to define object instance information in the constructor.

Prototype is a very important concept, in an article to understand the relationship between Proto and prototype and the difference between the very detailed

A simpler notation.

1 function Person () {  2} 3 Person.prototype = {  4  name: ' Jiang ',  5  job: ' Student ', 6   sayname:function () {  7    console.log (this.name)  8   }  9} var person1 = new Person ()

Set Person.prototype to equal to an object created as an object literal, but will cause. constructor not pointing to person.

In this way, the default Person.prototype object is completely overridden, so. Constructor doesn't exist here.

1 Person.prototype.constructor = = = Person  //False

If you need this property, you can manually add

1 function Person () {  2} 3 Person.prototype = {  4  constructor:person  5  name: ' Jiang ', 6   job: ' Student ',  7  sayname:function () {  8     Console.log (this.name)  9  }

But this way is still not good enough, should be for the constructor property by default is not enumerable, so directly set, it will be enumerable. So when you can, Object.defineproperty method

1 Object.defineproperty (Person.prototype, ' constructor ', {2  enumerable:false,3    Value:person4 })

Disadvantages

Using prototypes, all attributes will be shared, which is a great advantage, with some drawbacks

All attribute instances in the prototype are shared by many instances, which is appropriate for the function. For those attributes that contain basic values, it is also possible, after all, that instance properties can mask prototype properties. But the reference type value will cause problems.

1 function Person () {2 }3 Person.prototype = {4 name: ' Jiang ',5 friends: [' Shelby ', ' Court ']6 }7 var person1 = new Person ()8 var person2 = new Person ()9 person1.friends.push (' Van ')Ten Console.log (person1.friends)//["Shelby", "Court", "Van"] One Console.log (person2.friends)//["Shelby", "Court", "Van"] AConsole.log (person1.friends = = = Person2.friends)//True

Friends exist with prototypes, instances Person1 and Person2 point to the same prototype, Person1 modify the referenced array, and also react to instance Person2

Combining the constructor pattern with the prototype pattern

This is the most widely used and most recognized way to create a custom type. It solves the drawbacks of those patterns above

Using this pattern allows each instance to have its own copy of an instance property, but also to share a reference to the method

That way, even if the instance property modifies the value of the reference type, it does not affect the property values of the other instances.

1 function Person (name) {2 this.name = name3 this.friends = [' Shelby ', ' Court ']4 }5 Person.prototype.sayName = function () {6 Console.log (this.name)7 }8 var person1 = new Person ()9 var person2 = new Person ()Ten person1.friends.push (' Van ') One Console.log (person1.friends)//["Shelby", "Court", "Van"] A Console.log (person2.friends)//["Shelby", "Court"] -Console.log (person1.friends = = = Person2.friends)//false

Dynamic Prototyping Mode

The dynamic prototype pattern encapsulates all information in a constructor, and when initialized, determines whether the prototype needs to be initialized by detecting a method that should exist.

1 function person (name, job) {2 //Properties3 this.name = name4 this.job = Job5  6 //Method7 if (typeof this.sayname!== ' function ') {8 Person.prototype.sayName = function () {9 Console.log (this.name)Ten     } One   } A   - } - var person1 = new Person (' Jiang ', ' Student ') thePerson1.sayname ()

It is added to the prototype only when the Sayname method does not exist. This code executes only when the constructor is first called.

The prototype has since been initialized and does not need to be modified

The modifications made to the prototype here can be immediately reflected in all instances

Second, if statements can be checked for any property or method that should exist after initialization, so it is not necessary to check each property and method with a large stack of if statements, just check one.

Parasitic constructor mode

The basic idea of this pattern is to create a function that encapsulates the code that creates the object, and then returns the newly created object

1 function person (name, job) {2 var o = new Object ()3 o.name = name4 o.job = Job5 o.sayname = function () {6 Console.log (this.name)7   }8 return o9 }Ten var person1 = new Person (' Jiang ', ' student ') OnePerson1.sayname ()

This pattern, in addition to using the new operator and using the wrapper function called the constructor, is almost the same as the factory pattern

constructor if you do not return an object, a new object is returned by default, and the value returned when the constructor is called can be overridden by adding a return statement at the end of the constructor function

Secure constructor Mode

The first thing to understand is that a safe object refers to the absence of a public attribute, and the method does not refer to this.

Secure objects are best suited for use in some security environments where this and new are prohibited, or when data is changed by other applications

The safe constructor pattern is similar to the parasitic pattern, with two different points: first, an instance method that creates an object does not reference this, but instead calls the constructor with the new operator

1 function person (name, job) {2 var o = new Object ()3 o.name = name4 o.job = Job5 o.sayname = function () {6 console.log (name)7   }8 return o9 }Ten var person1 = person (' Jiang ', ' student ') OnePerson1.sayname ()

As with the parasitic constructor pattern, there is no relationship between the created object and the constructor, and the instanceof operator has no meaning for them.

Seven ways JavaScript creates objects

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.