Several important patterns of JavaScript creation objects

Source: Internet
Author: User

First, the Factory mode 1. code example
function person(name, age) {  var p = new object();  p.name = name;  p.age = age;  p.sayName = function() {    console.log(this.name);  };  return p;}var person1 = person(‘Bonnie‘, 26);var person2 = person(‘Summer‘, 24);
2. Advantages

Resolves an issue that creates multiple similar objects.

3. Disadvantages

No problem was resolved for object recognition.

Second, the constructor mode 1. code example
function Person(name, age) {  this.name = name;  this.age = age;  this.sayName = function() {    console.log(this.name);  }}var person1 = new Person(‘Bonnie‘, 26);var person2 = new Person(‘Summer‘, 24);

Remember: The constructor returns an instance of the new object (constructor mode) by default, without returning a value . If you add a return statement at the end of the constructor, you can override the value returned when the constructor is called (parasitic constructor mode).

2. Advantages

Creating a custom constructor means that its example can be flagged as a specific type (execution Person1 instanceof person is true). This is where it beats the factory model.

3. Disadvantages

Each method is created once on each instance. That is, each instance created with the constructor pattern contains its own unique function with the same name. However, it is not necessary to create two functions with the same name to accomplish the same task.

Each instance that the constructor creates can be referenced by a method like this:

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

However, the problem is that this method, which is referenced by different instances of the constructor, exists in the global scope, which destroys the global scope and, on the other hand, destroys the encapsulation of the custom type.

Three, prototype mode 1. code example
function Person() {}Person.prototype.name = "Bonnie";Person.prototype.age = 26;Person.prototype.sayName = function() {  console.log(this.name)}var person1 = new Person();var person2 = new Person();
2. Advantages

You can have all object instances share the properties and methods that it contains.

3. Disadvantages

First, it omits the process of passing initialization parameters to the constructor so that all instances will get the same property value by default.

What's more, the nature of its sharing is very inappropriate for attribute values (such as arrays) of reference types: for modifying the property value of a reference type on one instance, this property value on the other instance is also modified. However, its shared nature is appropriate for functions, because methods are inherently common. Its properties for base values are also appropriate, because properties in the prototype can be overridden by adding property names with the same name on the instance.

See my other blog, prototype and prototype chain, "one, the important mode of creating objects: Prototype Mode".

Iv. combining the constructor pattern with the prototype pattern 1. code example
function Person(name, age) {  this.name = name;  this.age = age;  this.friends = [‘Spring‘, ‘Huiyun‘];}Person.prototype.sayName = function() {  console.log(this.name);}var person1 = person(‘Bonnie‘, 26);var person2 = person(‘Summer‘, 24);
2. Advantages

Instance properties are implemented in constructors, and shared properties and methods are defined in the prototype as a way to create custom types with the widest and most agreeable. is also the default mode.

Five, dynamic prototype mode 1. code example
function Person(name, age) {  this.name = name;  this.age = age;  if (typeof this.sayName != ‘function‘) {    Person.prototype.sayName = function() {      console.log(this.name);    }  }}
2. Advantages

The method is added to the prototype only if a method does not exist. The code added to the prototype will only be executed when the constructor is first called. Modifications made to the prototype are immediately reflected in all instances.

Note: You cannot use object literals to rewrite the prototype, because if an instance has already been created, rewriting the prototype will cut off the connection between the existing instance and the new prototype.

Six, parasitic constructor mode 1. code example
function Person(name, age) {  var o = new Object();  o.name = name;  o.age = age;  o.sayName = function() {    console.log(this.sayName);  }  return o;}var person1 = new Person(‘Bonnie‘, 26);

This pattern is identical to the factory pattern except that the new operator is used and the wrapper function is called a constructor. The constructor returns the new object instance by default without returning a value. Instead, you can override the value returned when the constructor is called by adding a return statement at the end of the constructor function.

2. Advantages

This pattern is suitable for creating instances of new properties, new methods for special objects such as array. That is, it is appropriate to create new special types (such as Specialarray) based on certain existing special types, such as array.

For example, you can create an array with an extra method on the basis of an array:

function SpecialArray() {  var o = new Array();  o.push.apply(o, arguments);  o.getPipedStr = function() {    return this.join(‘|‘);  }  return o;}var colors = new SpecialArray(‘red‘, ‘blue‘, ‘green‘);console.log(colors);// ["red", "blue", "green", getPipedStr: ?]console.log(colors.getPipedStr);//"red|blue|green"
3. Disadvantages

The object returned by this pattern has no relation to the constructor and the prototype of the constructor. That is, the pattern returns objects that are no different from super-many objects outside the constructor. Therefore, the type represented by the constructor is not the type of the instance.

For the above example:

colors instanceof SpecialArray;// false
Seven, the safe structural function mode 1. code example
function Person(name, age) {  var o = new Object();  //私有变量  var job = ‘developer‘;  o.sayName = function() {    console.log(name);  }  o.sayJob = function() {    console.log(job);  }  return o;}var person1 = new Person(‘Bonnie‘, 26);person.sayName()//‘Bonnie‘person.sayJob()//‘Job‘

In addition to the Sayname and Sayjob methods, there is no way to access the variable name, job, or object created by this method.

2. Advantages

This pattern provides a fixed way to access the raw data in the constructor (constructor arguments, private variables). In addition to the methods provided, there is no way to access the original data in its constructor. This security makes the secure constructor pattern ideal for use in certain secure execution environments, such as Adsafe, Caja.

Resources

"Javascirpt Advanced Programming" 6.2

Several important patterns of JavaScript creation objects

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.