This is the 23rd day of my participation in Gwen Challenge

preface

There are many new properties, methods, and features in ES6, and this series will re-learn ES6 through simulation implementations to help you better understand those new things.

Objective: To simulate new methods of implementing objects

Analog implementation

Description:

  1. Explain the usage briefly, and then simulate the implementation
  2. The real implementation is not necessarily implemented like this, but only implements functionality for understanding

Object.is()

usage

This method is used to optimize two problems where === : NaN does not equal NaN, and +0 equals -o

Simulation implementation:_ismethods

Object._is = function (one, two) {
    if (Number.isNaN(one) && Number.isNaN(two)) {
        return true;
    }
    if (one === 0 && two === 0) {
        if (1 / one < 0 && 1/two >0) {return false
        }
        if (1 / one > 0 && 1/two <0) {
            return false}}return one === two;
}
console.log(Object._is(NaN.NaN));//true
console.log(Object._is(+0, -0));//false
console.log(Object._is(-0, +0));//false
Copy the code

Here’s a trick to determine whether a number is +0 or -0. Normally, it’s hard to determine because they’re all equal to 0, but I can use the law that a positive number divided by +0 equals Infinity, and divided by -0 equals -infinity, to compare Infinity and -infinity to 0, respectively. So we can figure out whether it’s minus 0 or plus 0

Object.assign()

usage

Assign is used to combine multiple objects to one object. The first argument is the target object to which other objects are to be merged, and the remaining arguments are the objects to be merged. Return target

Simulation implementation:_assignmethods

Object._assign = function () {
    if (arguments.length == 0) {
        throw new TypeError(`Cannot convert undefined or null to object`);
    }
    if (arguments.length == 1) {
        return arguments[0];
    }
    if (arguments.length >= 2) {
        let target = arguments[0];
        for (let i = 1; i < arguments.length; i++) {	
            (arguments[0]); // Select arguments from arguments[0].
            for(let key in arguments[i]){
                    // Key represents the attributes of each object to be merged, and can be added directly to the target
                    target[key] = arguments[i][key]; }}return target
    }
}
let obj1 = { name: 'a' };
let obj2 = { name: 'b' }
console.log(Object._assign(obj1, obj2));
Copy the code

Object.getPrototypeOf()

usage

The prototype used to get the object

Simulation implementation:_getPrototypeOfmethods

Object._getPrototypeOf = function (target) {
    return target.__proto__;
}
Copy the code

Object.setPrototypeOf()

usage

Used to set the prototype of the object

Simulation implementation:_getPrototypeOfmethods

Object._setPrototypeOf = function (target, proto) {
    target.__proto__ = proto;
}

Copy the code

Object.create()

use

Object.create() is used to generate a new Object with the specified prototype, and returns that Object. The first argument can be an object or null, which indicates that the object has no stereotype.

Simulation implementation:_createmethods

Object._create = function(proto){
    let obj = {}
    Object.setPrototypeOf(obj,proto)
    return obj
}
Copy the code

Object.keys(), object.values (), Object.entries()

usage

Object.keys() is a new ES5 method that returns an array of Object keys

Object.values and object. entries are methods introduced in ES2017 to return an array of Object values and an array of key-value pairs of keys and values, respectively

And since it’s what you put in ES6 when you comb through it, let’s write it down

Simulation implementation:_keys,_values,_entries

  • _keys implementation
Object._keys = function(o){
    let res = [];
    for(let key in o){
        res.push(key)
    }
    return res;
}
console.log(Object._keys(obj));//["a", "b", "c"]
Copy the code
  • _values implementation
Object._values = function(o){
    let res = [];
    for(let key in o){
        res.push(o[key]);
    }
    return res;
}
let obj = {a:1.b:2.c:3};
console.log(Object._values(obj));/ / [1, 2, 3]
Copy the code
  • _entries implementation
Object._entries = function(o){
    let res = [];
    for(let key in o){
        res.push([key,o[key]]);
    }
    return res;
}
let obj = {a:1.b:2.c:3};
console.log(Object._entries(obj));//[["a", 1], ["b", 2], ["c", 3]]
Copy the code

Object.fromEntries()

usage

Equivalent to creating an object, it turns an array of key-value pairs into an object.

So the array format passed must look like this [[‘name’,’Alice’],[‘age’,12],…]

Analog implementation

Object._fromEntries = function(arr){
    // Accept an array
    if(Array.isArray(arr)){
        // Each entry must also be an array of length 2
        let isTwoLengthArray = arr.some(val= >{
            return Array.isArray(val) &&  val.length == 2 
        });
        if(isTwoLengthArray){
            let obj = {}
            arr.forEach(val= > {
                obj[val[0]] = val[1]});return obj
        }
    }
    // It is possible to implement data structures such as maps
}
let person = [['name'.'Alice'], ['age'.12]]
console.log(Object._fromEntries(person))//{name: "Alice", age: 12}
Copy the code

Object.getOwnPropertyDescriptors()

usage

This method was actually introduced in ES2017 to return a description of all of the object’s own properties passed in

Simulation implementation:_getOwnPropertyDescriptorsmethods

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

__proto__ properties

usage

A prototype object used to return an incoming object

Simulation implementation:_proto_

Object.prototype._proto_ = Object.getPrototypeOf(obj);
Copy the code

END

That’s a mock implementation of the new properties and methods on ES6 objects!

I know there are many problems to be solved, but as long as I am familiar with what these methods do, I have achieved the purpose of this study!

If you have any questions or suggestions, please leave a message. Thank you!