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

MySQL slow query and query reconstruction method record

Preface What is a slow query and how to optimize ...

Example analysis of the page splitting principle of MySQL clustered index

This article uses an example to illustrate the pa...

Best Practices Guide for Storing Dates in MySQL

Table of contents Preface Do not use strings to s...

MySQL 8.0.16 installation and configuration graphic tutorial under macOS

This article shares the installation and configur...

How to create, save, and load Docker images

There are three ways to create an image: creating...

How to limit the value range of object keys in TypeScript

When we use TypeScript, we want to use the type s...

Implementation of debugging code through nginx reverse proxy

background Now the company's projects are dev...

Detailed explanation of Vue's list rendering

Table of contents 1. v-for: traverse array conten...

How to add file prefixes in batches in Linux

You need to add "gt_" in front of the f...

Introduction and use of five controllers in K8S

Table of contents Controller type of k8s Relation...

Public free STUN servers

Public free STUN servers When the SIP terminal us...

Detailed example of SpringBoot+nginx to achieve resource upload function

Recently, I have been learning to use nginx to pl...

Solution to Element-ui upload file upload restriction

question Adding the type of uploaded file in acce...