Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

1. Object.getOwnPropertyDescriptors

1.1 introduction

ES5 Object. GetOwnPropertyDescriptor method returns an Object attribute description of Object (descriptor), ES2017 introduced Object. GetOwnPropertyDescriptors method, Returns a description object that defines all of the object’s own properties (non-inherited properties).

Use:

const obj = {
  name: 'the little _Battle'.get test() {
    return 'the nuggets'}}Object.getOwnPropertyDescriptors(obj)
// { name:
// {value: 'small _Battle',
// writable: true,
// enumerable: true,
// configurable: true },
// test:
// { get: [Function: get test],
// set: undefined,
// enumerable: true,
// configurable: true } }
/ / implementation of this method is based on the ES5 Object. The getOwnPropertyDescriptor ()

const getOwnPropertyDescriptors = (obj) = > {
  const res = {}
  for (let key of Reflect.ownKeys(obj)) {
    res[key] = Object.getOwnPropertyDescriptor(obj, key)
  }
  return res
}
Copy the code

Object.assign() cannot copy the get and set attributes correctly. And we can use the Object. DefineProperties () Object. GetOwnPropertyDescriptor to achieve correct shallow copy.

const source = {
  name: 'the little _Battle'.set test(val) {
    console.log(val)
  }
}
const res = {}
Object.defineProperties(res, Object.getOwnPropertyDescriptors(source))
Object.getOwnPropertyDescriptors(res)
// { name:
// {value: 'small _Battle',
// writable: true,
// enumerable: true,
// configurable: true },
// test:
// { get: [Function: get test],
// set: undefined,
// enumerable: true,
// configurable: true } }
The typical way to create a subclass is to define a subclass, set its prototype to an instance of the superclass, and then define properties on that instance. It's not very elegant, especially for getters and setters. You can set the prototype as follows: */

function superclass() {}
superclass.prototype = {
  // Define methods and properties here
}
function subclass() {}
subclass.prototype = Object.create(
  superclass.prototype,
  Object.getOwnPropertyDescriptors({
    // Define methods and properties here}),)Copy the code

2. Object.values/Object.entries

2.1 introduction

ES2017 has two new functions, Object.values and Object.entries

The object. values method returns an array of all the enumerable property values of a given Object itself

The Object.entries method returns an array of key-value pairs for a given Object’s own enumerable properties, traversed in ascending order if the property’s key is numeric.

2.2 the Object values

const obj = { name: '_Battle'.address: 'juejin' }

Object.values(obj) // ['_Battle', 'juejin']
Copy the code

When the attribute key is a number

const obj = { 2: '_Battle'.1: 'juejin' }
Object.values(obj) // ['_Battle', 'juejin']
Copy the code

Only the object’s own traversable property is returned. If the property is an object, the object must have the Enumerable property enabled otherwise it is not returned.

const obj = Object.create({}, {name: { value: 1 }})
Object.values(obj) / / []
 
const obj = Object.create({}, {name: { value: 1.enumerable: true }})
Object.values(obj) / / [1]
Copy the code

If the attribute value is Symbol, object. values filters attributes whose attribute Key is Symbol

Object.values({ [Symbol()] :123.name: '_Battle' }) // '_Battle'
Copy the code

If the argument is not an Object, such as a value or a Boolean, object. values does not add non-inherited attributes to the instance, so an empty array is returned if the argument is a string, an array of characters is returned

Object.values('_Battle')
// ['_', 'B', 'a', 't', 't', 'l', 'e']
Copy the code

2.3 Object. Entries

Object.entries(), which returns an iterable to iterate through the Object’s properties

const obj = { a: 5.b: 7.c: 9 }
for (const [key, value] of Object.entries(obj)) {
  console.log('key', key, 'value', value)
}
// key: a, value: 5
// key: b, value: 7
// key: c, value: 9
// Convert Object to Map
new Map(a)// The constructor accepts an iterable entry. You can easily convert objects to maps using the object. entries method:

var obj = { foo: 'bar'.baz: 42 }
var map = new Map(Object.entries(obj))
 
console.log(map)
// Map { foo: "bar", baz: 42 }
Copy the code

3. String padStart() & padEnd()

3.1 introduction

In String, ES2017 added two new functions, String completion length. If the string is not of a specified length, it is incomplete at the head or tail. PadStart () is used for head completion and padEnd() for tail completion.

grammar

str,padStart(targetLength [, String])
str,padEnd(targetLength [, String])
/** parameter (1) targetLength: the targetLength to which the current string is to be filled. If this value is less than or equal to the string length, the string itself is returned. Otherwise, fill the String left or right based on the excess length. (2) padString: Optional padding character. The default value is "" */
Copy the code

use

// If targetLength is less than or equal to the length of the string:
'xxx'.padStart(2.'ab') // 'xxx'
'xxx'.padEnd(2.'cd') // 'xxx'
// If targetLength is greater than the length of the string:

'abc'.padStart(10.'0123456789')
// '0123456abc'
// If the second argument is omitted, Spaces are used to complete the length by default.

'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
Copy the code

4. Trailling-function-commas

Function argument lists allow comma endings

4.1 introduction

ES2017 allows a trailing comma as the last parameter of a function. Previously, functions were defined and called without a comma as the last parameter.

grammar

function test(param1, param2,)
Copy the code

5 Shared Memory and Atomics

5.1 introduction

Javascript is a single thread, while Web workers introduce multithreading. The main thread is used to interact with users and the Worker thread is used to undertake computing tasks. Data for each thread is isolated and communicated via postMessage. The main thread

const w = new Worker('worker.js')
w.postMessage('hello')
w.onmessage = function (res) {
  console.log(res.data) 
}
// worker.js communicates with the main thread via postMessage().

onmessage = function (res) {
  console.log(res.data)
  postMessage('hello')}Copy the code

5.2 SharedArrayBuffer object

Introduction: Data exchange between threads can be in a variety of formats, and the data exchange mode is the replication mechanism. That is, one process makes a copy of the data it wants to share and sends it to another process using the postMessage method. If the amount of data is large, the communication efficiency is low. In this case, you can use shared memory to improve the communication efficiency.

The SharedArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data, similar to the ArrayBuffer object, but capable of sharing data.

// We can create shared memory objects in the main thread

/ / main thread

const w = new Worker('worker.js')
// create 1KB shared memory
const shareBuffer = new SharedArrayBuffer(1024)
// Share memory address via postMessage communication
w.postMessage(shareBuffer)
// Create a view on shared memory for data writing
const sharedArray = new Int32Array(sharedBuffer)
Worker.js

onmessage = function (res) {
  // Access shared memory
  const sharedBuffer = res.data
  // Access the read-write area
  const sharedArray = new Int32Array(sharedBuffer)
  // At this point our worker thread can read and write to the shared read-write area
  sharedArray[0] = 100
  console.log(sharedArray) // Int32Array(256) [100, 0, ...., 0]
}
Copy the code

5.3 Atomics Objects implement atomic operations

Introduction: Multithreading shared memory, need to pay attention to an important problem is: prevent two threads modify the same memory address at the same time; In other words, when one thread changes SharedArray, it needs to be synchronized to another thread. ES2017’s SharedArrayBuffer API provides Atomics objects that guarantee that all shared memory operations are “atomic” and that each operation is synchronized across all threads.

Atomicity: Multiple threads that share memory can simultaneously read and write data in the same location. Atomic operations ensure that the data being read or written is as expected, that is, the next atomic operation is executed after the last operation.

/ / syntax:Atomics.store(): used to write data to shared memory and return this value; Atomics.load(): Used to fetch data from shared memory. Atomics.exchange(): Used to modify data from shared memory. Atomics.store(typedArray, index, value)// typedArray is a **shared** array of the specified type
Atomics.load(typedArray, index) // Retrieve the corresponding position dataUse, read, write, modify and other atomic operationsconst buffer = new SharedArrayBuffer(1024)
const array = new Unit8Array(buffer)
Atomics.store(array, 0.12) / / 12
Atomics.store(array, 0) / / 12
Atomics.exchange(array, 0.11) / / 11
Copy the code

5.4 Use atomics. wait and atomics. notify to lock memory (let other threads sleep)

Worker.js

self.addEventListener(
  'message',
  (event) => {
     const sharedArray = new Int32Array(event.data) // Read shared memory
     const expectIndex = 0, expectValue = 10
     Atomics.wait(sharedArray, expectIndex, expectValue) // Wait: when sharedArray[expectIndex] === expectValue, worker.js will start to sleep and wait to wake up.
     console.log(Atomics.load(sharedArray, index))
   }
)
/ / main thread
const shareBuffer = new SharedArrayBuffer(1024)
const sharedArray = new Int32Array(sharedBuffer)
Atomics.store(sharedArray, 0.100) // The main thread writes data atoms
Atomics.notify(sharedArray, 0.1) // notify: wake up a thread at position 0 in sharedArray memory
// Note: the browser main thread is not suitable for setting sleep, which will cause the user to become unresponsive. And in fact, the browser main thread rejects Atomics.wait
Copy the code

Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.

Past wonderful recommendation

ES Series summary (1)

Front-end common encryption methods

Canvas Pit Climbing Road

Don’t know SEO optimization? An article helps you understand how to do SEO optimization

Canvas Pit Road

Wechat small program development guide and optimization practice

Talk about mobile adaptation

Front-end performance optimization for actual combat

Talk about annoying regular expressions

Obtain file BLOB stream address to achieve the download function

Vue virtual DOM confused? This article will get you through the virtual DOM once and for all

Git Git

Easy to understand Git introduction

Git implements automatic push

How do I use Git in my work

Interview Recommendations

Front ten thousand literal classics – the foundation

Front swastika area – advanced section

More exciting details: personal homepage