Detailed explanation of several ways to create objects and object methods in js

Detailed explanation of several ways to create objects and object methods in js

This article is the second article about objects written in Chapter 8 of the JS Red Book.

Several modes for creating objects:

Factory pattern:

Factory means function. The core of the factory pattern is to define a function that returns a new object.

 function getObj(name, age) {
  let obj = {}
  obj.name = name
  obj.age = age
  return obj
 }
 let person1 = getObj("cc", 31)

Disadvantage: Don’t know what type the newly created object is

Constructor pattern:

Get an object instance through a constructor.
The difference between the constructor and the factory pattern is:
1. Add this to the constructor function body
2. The constructor has no return
3. When calling the constructor, use the new keyword

 function CreateObj(name, age) {
  this.name = name
  this.age = age
 }
 let person1 = new CreateObj("cc", 31)
 console.log(person1)
 console.log(person1.constructor === CreateObj); // true
 console.log(person1 instanceof CreateObj); // true

Two questions about constructors:

1. The only difference between a constructor and an ordinary function is the calling method. The constructor must use the new keyword. If new is not used, attributes are added to the Global object. In the following example, the CreateObj method adds the name and age attributes to the window object.

 function CreateObj(name, age) {
  this.name = name
  this.age = age
 }
 CreateObj('cc', 10)
 console.log(window.name) // 'cc'

2. Problems with the constructor: The methods in the constructor are created once each time an instance is created.

person1.sayName() === person2.sayName() // false

The solution is to define sayName outside of createObj.

 function sayName() {
  console.log(this.name)
 }
 function CreatePerson(name, age) {
  this.name = name
  this.age = age
  this.sayName = sayName
 }
 let person1 = new CreatePerson('joy', 31)
 person1.sayName()

However, this will prevent the code referenced by custom types from being grouped together well.

Prototype mode:

The principle is that every function has a prototype property. Prototype is an object whose properties and methods are shared by all instances.
There are two equations about the prototype pattern:

 function Person() { }
 let person1 = new Person()
 console.log(person1.__proto__ === Person.prototype) // true
 console.log(Person.prototype.constructor === Person); // true

Three methods about prototype objects: isPrototype, getPrototypeof, setPrototypeOf, Object.create()

// isPrototypeOf determines whether the prototype object of the constructor is the prototype object of the instance function Person() {}
 let person1 = new Person()
 console.log(Person.prototype.isPrototypeOf(person1)); // true
// Get the prototype object of the object function Person() {}
 let person1 = new Person()
 console.log(Object.getPrototypeOf(person1) === Person.prototype);
// Set an object as the prototype object of another object let person1 = {name: "cc"}
 let person2 = {age: 32}
 Object.setPrototypeOf(person1,person2)
 console.log(person1.name, person1.age); // cc 32
// Create a new object with an object as the prototype object let person1 = {name: "cc"}
 let person2 = Object.create(person1)
 person2.age = 30
 console.log(person2.name, person2.age);

When accessing the name attribute of an object person, follow these steps:
1. If person has a name attribute (even if this attribute is null, null will be returned), return the name attribute value; if not, continue to look for it on the prototype object Person.prototype
2. If there is a name attribute on the prototype, return the name attribute value on the prototype; if not, return undefined

To determine whether a property is on an instance or on a prototype, you can use hasOwnProperty

 function Person() {}
 Person.prototype.name = "cc"
 let person1 = new Person()
 console.log(person1.name) // 'cc'
 console.log(person1.hasOwnProperty("name")); // false

To determine whether an object has a certain attribute, use the in operator

// Return true if found in the object itself or prototype 
function Person() {}
 Person.prototype.name = "cc"
 let person1 = new Person()
 console.log("name" in person1) // true
 console.log(person1.hasOwnProperty("name")); // false

Methods for accessing object properties:

Object.keys()
for ... in // Inherited properties are also traversed Object.getOwnPropertyNames(obj) // Lists both enumerable and non-enumerable properties, and the rest are the same as Object.keys() Object.getOwnPropertySymbols(obj) // Similar to getOwnPropertyNames, but only for symbols
Reflect.ownKeys(obj) // Same result as Object.keys()

Other ways to access object properties and property values:
Object.values() is an array of object values, omitting the Symbol type.
Object.entries() is an array of object key-value pairs, which converts the key into a string, omitting the Symbol type.

 function Person() {}
 Person.prototype.name = "cc"
 let person = new Person()
 person.age = 21
 let sy = Symbol('sy')
 person[sy] = 'smile'
 console.log(Object.values(person)) // [ 21 ]
 console.log(Object.entries(person)) // [ [ 'age', 21 ] ]

This concludes this article on several ways and methods of creating objects in js. For more relevant content on creating objects in js, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of various ways to create objects in js and their advantages and disadvantages
  • Summary of JavaScript object-oriented object creation method
  • How to create functions and objects in JS
  • Summary of JavaScript object creation methods [factory pattern, constructor pattern, prototype pattern, etc.]
  • Summary of common ways to create objects in JavaScript
  • Summary of common ways to create custom objects in JavaScript
  • A comprehensive summary of seven ways to create objects in JavaScript
  • Analysis of common methods and principles of creating JS objects
  • Seven ways to create objects in JavaScript (recommended)
  • Four ways to create objects in JS

<<:  Detailed explanation of Docker data management (data volumes & data volume containers)

>>:  MySQL uses inet_aton and inet_ntoa to process IP address data

Recommend

About the problems of congruence and inequality, equality and inequality in JS

Table of contents Congruent and Incongruent congr...

Tutorial on how to install htop on CentOS 8

If you are looking to monitor your system interac...

Introduction to Docker Architecture

Docker includes three basic concepts: Image: A Do...

How to quickly set the file path alias in react

React is a JavaScript library for building user i...

Let's talk about the difference between containers and images in Docker

What is a mirror? An image can be seen as a file ...

How to query the latest transaction ID in MySQL

Written in front: Sometimes you may need to view ...

Details of 7 kinds of component communication in Vue3

Table of contents 1. Vue3 component communication...

JavaScript using Ckeditor + Ckfinder file upload case detailed explanation

Table of contents 1. Preparation 2. Decompression...

Introduction to Apache deployment of https in cryptography

Table of contents Purpose Experimental environmen...

Linux kernel device driver memory management notes

/********************** * Linux memory management...

Detailed explanation of two points to note in vue3: setup

Table of contents In vue2 In vue3 Notes on setup ...

Common shell script commands and related knowledge under Linux

Table of contents 1. Some points to remember 1. V...

Detailed explanation of the background-position percentage principle

When I was helping someone adjust the code today,...

Overview of the basic components of HTML web pages

<br />The information on web pages is mainly...