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

Jun 04, 2017 am 10:38 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem that activex components cannot create objects How to solve the problem that activex components cannot create objects Jan 24, 2024 pm 02:48 PM

Solution: 1. Check spelling and path; 2. Add reference to component; 3. Check registry; 4. Run as administrator; 5. Update or repair Office; 6. Check security software; 7. Use other versions Components; 8. View error messages; 9. Find other solutions. Detailed introduction: 1. Check spelling and path: Make sure there are no spelling errors in the name and path of the object, and the file does exist in the specified path; 2. Add references to components, etc.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

What are the advantages and disadvantages of templating? What are the advantages and disadvantages of templating? May 08, 2024 pm 03:51 PM

Templating: Pros and Cons Templating is a powerful programming technique that allows you to create reusable blocks of code. It offers a range of advantages, but also some disadvantages. Pros: Code Reusability: Templating allows you to create common code that can be reused throughout your application, reducing duplication and maintenance efforts. Consistency: Templating ensures that code snippets are implemented the same way in different locations, improving code consistency and readability. Maintainability: Changes to a template are reflected simultaneously in all code that uses it, simplifying maintenance and updates. Efficiency: Templating saves time and effort because you don't have to write the same code over and over again. Flexibility: Templating allows you to create configurable blocks of code that can be easily adapted to different application needs. shortcoming

Must read before purchasing a system: Analysis of the advantages and disadvantages of Win11 and Win10 Must read before purchasing a system: Analysis of the advantages and disadvantages of Win11 and Win10 Mar 28, 2024 pm 01:33 PM

In today's information age, personal computers play an important role as an indispensable tool in our daily lives. As one of the core software of computers, the operating system affects our usage experience and work efficiency. In the market, Microsoft's Windows operating system has always occupied a dominant position, and now people face the choice between the latest Windows 11 and the old Windows 10. For ordinary consumers, when choosing an operating system, they do not just look at the version number, but also understand its advantages and disadvantages.

What are the advantages and disadvantages of how Java Servlets work? What are the advantages and disadvantages of how Java Servlets work? Apr 16, 2024 pm 03:18 PM

JavaServlet is a Java class used to build dynamic web pages and serves as a bridge between client and server. Working principle: receive requests, initialize Servlet, process requests, generate responses and close Servlet. Pros: Portable, scalable, secure and easy to use. Disadvantages: Overhead, coupling, and state management. Practical case: Create a simple Servlet to display the "Hello, Servlet!" message.

Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Comparison of the advantages and disadvantages of PHP frameworks: Which one is better? Jun 04, 2024 pm 03:36 PM

The choice of PHP framework depends on project needs and developer skills: Laravel: rich in features and active community, but has a steep learning curve and high performance overhead. CodeIgniter: lightweight and easy to extend, but has limited functionality and less documentation. Symfony: Modular, strong community, but complex, performance issues. ZendFramework: enterprise-grade, stable and reliable, but bulky and expensive to license. Slim: micro-framework, fast, but with limited functionality and a steep learning curve.

Golang compiler summary: explore the advantages and disadvantages of various compilers Golang compiler summary: explore the advantages and disadvantages of various compilers Jan 19, 2024 am 10:44 AM

With the development of Golang, more and more compilers have been developed. When choosing a compiler, developers need to consider many factors, such as reliability, performance, ease of use, etc. This article will summarize some common Golang compilers and explore their advantages and disadvantages to help developers better choose the compiler that suits them. Go official compiler Go official compiler is Golang's default compiler and a widely recognized compiler in the Golang community. It has the following advantages: good stability, small size and compilation

See all articles