Table of Contents
1 new Object()
2 Object literal method
3 Factory Pattern
4 Constructor pattern
5 Prototype pattern
6 Combine the constructor pattern and the prototype pattern
7 Dynamic prototype mode
8 Safe constructor pattern
Home Web Front-end JS Tutorial What are the modes for creating objects?

What are the modes for creating objects?

Jun 26, 2017 am 11:29 AM
create object model

1 new Object()

First create an Object instance, and then add properties and methods to it

var Person = new Object()
Person.name = 'hl'
Person.sayName = function () {
  console.log(this.name)
}
Copy after login

2 Object literal method

The object literal method is The fastest and most convenient way to create objects, it is used in many scenarios.

var Person = {
  name: 'hl',
  sayName: function () {
    console.log(this.name)
  }
}
Copy after login

The disadvantage of the object literal method is that when creating multiple objects of the same type, a lot of duplicate code will be generated, so there is a factory pattern.

3 Factory Pattern

Factory pattern uses functions to encapsulate the details of creating objects. When calling the function, pass in the object properties and then return an object.

function createPerson (name) {
  return {
    name: name,
    sayName: function () {
      console.log(this.name)
    }
  }
}
var person = createPerson('hl')
var person = new createPerson('hl') // 寄生构造函数模式
Copy after login

The same result can also be obtained by using the new operator. This method is called the parasitic constructor pattern, and (should) be no different from calling the function directly.
Although the factory pattern solves the problem of creating multiple objects of the same type, it cannot identify the specific type of the object.

4 Constructor pattern

For objects created through the constructor, you can use the instanceof operator to determine the type of the object. According to programming convention, constructor names should be capitalized to distinguish them from ordinary functions.

function Person (name) {
  this.name = name
  this.sayName = function () {
    console.log(this.name)
  }
}
p = new Person('hl')
p instanceof Person // true
Copy after login

Characteristics of the constructor:

  • No explicit creation of objects

  • Attributes and methods are directly assigned to this

  • No return statement

  • Use the new operator to create objects

The disadvantage of the constructor is that each The method will be recreated on each instance, causing a waste of memory.

5 Prototype pattern

Using the prototype pattern, you can easily add properties and methods to objects.

function Person () {
}
var p = new Person()
Person.prototype.name = 'hl'
Person.prototype.sayName = function () {
  console.log(this.name)
}
p.sayName() // hl
Copy after login

The prototype is dynamic, that is, the object is created first and then the prototype is modified, and the instance can also obtain the corresponding properties and methods.
The prototype mode is not without its shortcomings. First, the prototype mode cannot pass initialization parameters, causing each instance to obtain the same properties; second, for reference type values, all instances refer to the same object, see below Example:

function Person () {
}
Person.prototype.relative = ['father','mother']

var person1 = new Person()
var person2 = new Person()
person1.relative.push('sister')
console.log(person2.relative) // [ 'father', 'mother', 'sister' ]
Copy after login

Modify the attributes of person1, and the attributes of person2 are also modified. Instances generally need to have their own attributes, so the prototype pattern is rarely used alone.

6 Combine the constructor pattern and the prototype pattern

The most common way to create objects is to combine the constructor pattern and the prototype pattern. Constructors are used for custom properties, and prototype patterns are used to define shared properties and methods.

function Person (name) {
  this.name = name
}
Person.prototype.sayName = function () {
  console.log(this.name)
}
Copy after login

7 Dynamic prototype mode

The prototype can be initialized in the constructor to better encapsulate the object creation process.

function Person(name) {
  this.name = name
  if (typeof this.sayName !== 'function') {
    Person.prototype.setName= function (name) {
      this.name = name
    }
    Person.prototype.sayName = function () {
      console.log(this.name)
    }
  }
}
Copy after login

You don’t have to use if to check every property or method, you only need to check one of the properties or methods that should exist after the prototype is initialized.

8 Safe constructor pattern

A safe object means that it has no public properties, its properties and methods do not reference this object, and the new operator is not used to create objects. Suitable for use in some environments that require security to prevent data from being modified.

function Person (name) {
  return {
    sayName: function () {
      console.log(name)
    }
  }
}
var person = Person('hl')
Copy after login

Objects created in safe mode have no way to modify and access the original data passed into the constructor except using the methods defined in the constructor.

The above is the detailed content of What are the modes for creating objects?. 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)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

How to create a family with Gree+ How to create a family with Gree+ Mar 01, 2024 pm 12:40 PM

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

How to Create a Contact Poster for Your iPhone How to Create a Contact Poster for Your iPhone Mar 02, 2024 am 11:30 AM

In iOS17, Apple has added a contact poster feature to its commonly used Phone and Contacts apps. This feature allows users to set personalized posters for each contact, making the address book more visual and personal. Contact posters can help users identify and locate specific contacts more quickly, improving user experience. Through this feature, users can add specific pictures or logos to each contact according to their preferences and needs, making the address book interface more vivid. Apple in iOS17 provides iPhone users with a novel way to express themselves, and added a personalizable contact poster. The Contact Poster feature allows you to display unique, personalized content when calling other iPhone users. you

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

See all articles