ES6 object new extension

Posted by karimali831 on Sun, 23 Jan 2022 17:38:12 +0100

ES6: object new extension

1, Attribute abbreviation

In ES6, when the object key name is equal to the corresponding value name, it can be abbreviated

const baz = {foo:foo}

// Equivalent to
const baz = {foo}

Methods can also be abbreviated

const o = {
  method() {
    return "Hello!";
  }
};

// Equivalent to

const o = {
  method: function() {
    return "Hello!";
  }
}

It also becomes much more convenient to return a value in a function

function getPoint() {
  const x = 1;
  const y = 10;
  return {x, y};
}

getPoint()
// {x:1, y:10}

Note: the abbreviated object method cannot be used as a constructor, or an error will be reported

const obj = {
  f() {
    this.foo = 'bar';
  }
};

new obj.f() // report errors

2, Property name expression

ES6 allows expressions to be placed in parentheses when defining objects with literals

let lastWord = 'last word';

const a = {
  'first word': 'hello',
  [lastWord]: 'world'
};

a['first word'] // "hello"
a[lastWord] // "world"
a['last word'] // "world"

Expressions can also be used to define method names

let obj = {
  ['h' + 'ello']() {
    return 'hi';
  }
};

obj.hello() // hi

Note that the attribute name expression and concise representation cannot be used at the same time, and an error will be reported

// report errors
const foo = 'bar';
const bar = 'abc';
const baz = { [foo] };

// correct
const foo = 'bar';
const baz = { [foo]: 'abc'};

Note that if the attribute name expression is an object, the object will be automatically converted to a string [object Object] by default

const keyA = {a: 1};
const keyB = {b: 2};

const myObject = {
  [keyA]: 'valueA',
  [keyB]: 'valueB'
};

myObject // Object {[object Object]: "valueB"}

3, super keyword

this keyword always points to the current object where the function is located. ES6 adds another similar keyword super to point to the prototype object of the current object

const proto = {
  foo: 'hello'
};

const obj = {
  foo: 'world',
  find() {
    return super.foo;
  }
};

Object.setPrototypeOf(obj, proto); // Set prototype object for obj
obj.find() // "hello"

4, Application of extension operator

In Deconstruction assignment, unread traversable attributes are assigned to the specified object

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }

Note: the deconstruction assignment must be the last parameter, otherwise an error will be reported

Deconstruction assignment is a shallow copy

let obj = { a: { b: 1 } };
let { ...x } = obj;
obj.a.b = 2; // Modify the key value of a attribute in obj
x.a.b // 2. It affects the value of x out of the structure

The extension operator of object is equivalent to using object Assign() method

5, Property traversal

ES6 has five methods to traverse the properties of objects.

  • for... in: loop through the object's own and inherited enumerable attributes (excluding Symbol attribute)

  • Object.keys(obj): returns an array, including the key names of all enumerable attributes (excluding Symbol attribute) of the object itself (excluding inheritance)

  • Object.getOwnPropertyNames(obj): returns an array containing the key names of all properties of the object itself (excluding Symbol properties, but including enumerable properties)

  • Object.getOwnPropertySymbols(obj): returns an array containing the key names of all Symbol properties of the object itself

  • Reflect.ownKeys(obj): returns an array containing all key names of the object itself (excluding inheritance), regardless of whether the key name is Symbol or string, and whether it is enumerable or not

The above traversal follows the same order rules for attribute traversal:

  • First, traverse all numeric keys and arrange them in ascending order
  • Secondly, traverse all the string keys and arrange them in ascending order according to the addition time
  • Finally, traverse all Symbol keys and arrange them in ascending order according to the addition time
Reflect.ownKeys({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 })
// ['2', '10', 'b', 'a', Symbol()]

6, Object adding method

The methods for adding objects are as follows:

  • Object.is()
  • Object.assign()
  • Object.getOwnPropertyDescriptors()
  • Object.setPrototypeOf(),Object.getPrototypeOf()
  • Object.keys(),Object.values(),Object.entries()
  • Object.fromEntries()

Object.is()

Strictly judging whether the two values are equal is basically the same as the behavior of the strict comparison operator (= =). There are only two differences: one is that + 0 is not equal to - 0, and the other is that NaN is equal to itself

+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

Object.assign()

Object. The assign () method is used to merge objects and copy all enumerable attributes of the source object source to the target object target

Object. The first parameter of the assign () method is the target object, and the following parameters are the source object

const target = { a: 1, b: 1 };

const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

Note: object The assign () method is a shallow copy, and it will be replaced in case of an attribute with the same name

Object.getOwnPropertyDescriptors()

Returns the description object of all its own properties (non inherited properties) of the specified object

const obj = {
  foo: 123,
  get bar() { return 'abc' }
};

Object.getOwnPropertyDescriptors(obj)
// { foo:
//    { value: 123,
//      writable: true,
//      enumerable: true,
//      configurable: true },
//   bar:
//    { get: [Function: get bar],
//      set: undefined,
//      enumerable: true,
//      configurable: true } }

Object.setPrototypeOf()

Object. The setprototypeof method is used to set the prototype object of an object

Object.setPrototypeOf(object, prototype)

// usage
const o = Object.setPrototypeOf({}, null);

Object.getPrototypeOf()

Prototype object used to read an object

Object.getPrototypeOf(obj);

Object.keys()

Returns an array of key names of all enumerable properties of itself (excluding inheritance)

var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]

Object.values()

Returns an array of key corresponding values of all enumerable properties of itself (excluding inheritance)

const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]

Object.entries()

Returns an array of key value pairs of all enumerable properties of an object itself (excluding inheritance)

const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

Object.fromEntries()

Used to convert an array of key value pairs into an object

Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }

Topics: Javascript Front-end ECMAScript