Home > Web Front-end > JS Tutorial > An in-depth understanding of the many ways JavaScript creates objects and their pros and cons

An in-depth understanding of the many ways JavaScript creates objects and their pros and cons

黄舟
Release: 2017-06-04 10:38:37
Original
1295 people have browsed it

This article mainly introduces the various ways and advantages and disadvantages of JavaScriptcreating objects. It mainly introduces 5 ways. If you are interested, you can learn about it

Written in front

This article explains Various ways of creating objects, with pros and cons.

But note:

This article is more like a note, because "JavaScript Advanced Programming" is so well written!

1. Factory Pattern

function createPerson(name) {
  var o = new Object();
  o.name = name;
  o.getName = function () {
    console.log(this.name);
  };

  return o;
}

var person1 = createPerson('kevin');
Copy after login

Disadvantages: Objects cannot be identified because all instances point to a prototype

2. ConstructorPattern

function Person(name) {
  this.name = name;
  this.getName = function () {
    console.log(this.name);
  };
}

var person1 = new Person('kevin');
Copy after login

Advantages: Instances can be identified as a specific Type

Disadvantages: Every time an instance is created, each method must be created once

2.1 Constructor pattern optimization

function Person(name) {
  this.name = name;
  this.getName = getName;
}

function getName() {
  console.log(this.name);
}

var person1 = new Person('kevin');
Copy after login

Advantages: Solve the problem of each method having to be recreated

Disadvantages: This What is encapsulation called...

3. Prototype mode

function Person(name) {

}

Person.prototype.name = 'keivn';
Person.prototype.getName = function () {
  console.log(this.name);
};

var person1 = new Person();
Copy after login

Advantages: Methods will not be recreated

Disadvantages: 1. All properties and methodsare shared 2. Cannot initialize parameters

3.1 Prototype Pattern optimization

function Person(name) {

}

Person.prototype = {
  name: 'kevin',
  getName: function () {
    console.log(this.name);
  }
};

var person1 = new Person();
Copy after login

Advantages: better encapsulation

Disadvantages: rewritten the prototype and lost the constructor attribute

3.2 Prototype mode optimization

function Person(name) {

}

Person.prototype = {
  constructor: Person,
  name: 'kevin',
  getName: function () {
    console.log(this.name);
  }
};

var person1 = new Person();
Copy after login

Advantages: instances can find their constructors through the constructor attribute

Disadvantages: There are still some shortcomings of the prototype pattern

4. Combined pattern

The constructor pattern and the prototype pattern are a perfect combination.

function Person(name) {
  this.name = name;
}

Person.prototype = {
  constructor: Person,
  getName: function () {
    console.log(this.name);
  }
};

var person1 = new Person();
Copy after login

Advantages: Shared sharing, private private, the most widely used method

Disadvantages: Some people just want to write everything together, that is, better encapsulation

4.1 Dynamic prototype mode

function Person(name) {
  this.name = name;
  if (typeof this.getName != "function") {
    Person.prototype.getName = function () {
      console.log(this.name);
    }
  }
}

var person1 = new Person();
Copy after login

Note: When using the dynamic prototype mode, the prototype cannot be overridden with object literals

Explain why:

function Person(name) {
  this.name = name;
  if (typeof this.getName != "function") {
    Person.prototype = {
      constructor: Person,
      getName: function () {
        console.log(this.name);
      }
    }
  }
}
 
var person1 = new Person('kevin');
var person2 = new Person('daisy');
 
// 报错 并没有该方法
person1.getName();
 
// 注释掉上面的代码,这句是可以执行的。
person2.getName();
Copy after login

To explain this problem, assume that var person1 = new Person('kevin') is started.

If you are not very familiar with the underlying execution process of new and apply, you can read the articles in the related links at the bottom.

Let’s review the implementation steps of new:

  1. First create a new object

  2. Then point the object’s prototype to Person.prototype

  3. Then Person.apply(obj)

  4. returns this object

Note at this time, review the implementation steps of apply, the obj.Person method will be executed, and the content in the if statement will be executed at this time. Note that the prototype attribute of the constructor points to the prototype of the instance, and uses literal method to directly override it. Person.prototype does not change the value of the prototype of the instance. person1 still points to the previous prototype, not Person.prototype. The previous prototype did not have a getName method, so an error was reported!

If you just want to write code in a literal way, you can try this:


function Person(name) {
  this.name = name;
  if (typeof this.getName != "function") {
    Person.prototype = {
      constructor: Person,
      getName: function () {
        console.log(this.name);
      }
    }
 
    return new Person(name);
  }
}
 
var person1 = new Person('kevin');
var person2 = new Person('daisy');
 
person1.getName(); // kevin
person2.getName(); // daisy
Copy after login

5.1 Parasitic constructor pattern


function Person(name) {
 
  var o = new Object();
  o.name = name;
  o.getName = function () {
    console.log(this.name);
  };
 
  return o;
 
}
 
var person1 = new Person('kevin');
console.log(person1 instanceof Person) // false
console.log(person1 instanceof Object) // true
Copy after login

The parasitic constructor pattern, I personally think it should be read like this:

Parasite-constructor-pattern, that is, a method that is parasitic on the constructor.

That is to say, under the guise of a constructor, you are trying to sell something like a sheep over someone else's head. You see, the created instance using instanceof cannot point to the constructor!

This method can be used in special situations. For example, if we want to create a special array with additional methods, but don’t want to directly modify the Array constructor, we can write like this:


function SpecialArray() {
  var values = new Array();
 
  for (var i = 0, len = arguments.length; i len; i++) {
    values.push(arguments[i]);
  }
 
  values.toPipedString = function () {
    return this.join("|");
  };
  return values;
}
 
var colors = new SpecialArray('red', 'blue', 'green');
var colors2 = SpecialArray('red2', 'blue2', 'green2');
 
 
console.log(colors);
console.log(colors.toPipedString()); // red|blue|green
 
console.log(colors2);
console.log(colors2.toPipedString()); // red2|blue2|green2
Copy after login

You will find that the so-called parasitic constructor pattern is actually better than the factory The pattern uses one more new when creating the object. In fact, the results of the two are the same.

But the author may hope to use SpecialArray like a normal Array. Although SpecialArray can be used as a function, this is not the author's intention and it becomes inelegant.

Do not use this mode when other modes can be used.

But it is worth mentioning that the loop in the above example:


for (var i = 0, len = arguments.length; i len; i++) {
  values.push(arguments[i]);
}
Copy after login

can be replaced by:


values.push.apply(values, arguments);
Copy after login

5.2 The so-called stable constructor pattern


function person(name){
  var o = new Object();
  o.sayName = function(){
    console.log(name);
  };
  return o;
}

var person1 = person('kevin');

person1.sayName(); // kevin

person1.name = "daisy";

person1.sayName(); // kevin

console.log(person1.name); // daisy
Copy after login

object, It refers to an object that has no public properties and its methods do not reference this.

There are two differences from the parasitic constructor pattern:

  1. The newly created instance method does not reference this

  2. Does not use the new operatorto call the constructor

Safe objects are best suited for some safety environment.

The safe constructor pattern is also the same as the factory pattern and cannot identify the type of the object.

The above is the detailed content of An in-depth understanding of the many ways JavaScript creates objects and their pros and cons. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template