ES6 practical methods Object.assign, defineProperty, Symbol

1. Merge objects-Object.assign()
Introduction
  • The assign method can assign multiple objects (dictionaries), syntax: Object.assign(srcObj,obj1,obj2...)
  • Duplicate keys will be overwritten (especially note that the object is overwritten), for enumerable (iterative) parameters (merged objects) if they are not objects, they will be automatically converted to object merge (such as string, []), for non-enumerable Parameters (undefined, null) will be skipped automatically.
  • If the source object (the first parameter) is not enumerable, an error will be reported
let srcObj= {
    
     a: 'a',b:'b',obj:{
    
    title:"我要被覆盖了"} },
obj1 = {
    
     b: 2 }, 
obj2 = {
    
     c: 3 },
str3 = "字符串",
num4 = 5;
obj = {
    
    newTitle:"我是新的title"} 

// 1.合并、重复覆盖、自动转换成对象合并、自动跳过举例:
console.log(Object.assign(srcObj, obj1 , obj2, str3, num4,obj));
// {a:'a',b:'2',c:3,0: "字",1: "符",2: "串",obj:{newTitle:"我是新的title"}}

// 2.报错
Object.assign(null, obj1 , obj2 )) 
Advanced
  • When an object is declared, its enumerable attribute is true by default, and we can also display it as false, so the object is not necessarily iterable (seeing is not necessarily true), but it can be taken by'.' To.
  • If the copy type is Symbol type, it will also be copied. Symbol: It is a data type like int, float, etc., except that it is a hidden type and cannot be accessed directly
// 1.跳过不可迭代的对象
var unEnumer = Object.defineProperty({
    
    }, "k", {
    
    
          enumerable: false,
          value: "hello"
        }), // {k:"hello"}
    // 这样定义对象,任何值都能作为键(被视为字符串)
    enumer = Object.defineProperty({
    
    }, null,{
    
    
          enumerable: true,
          value: "hello"
        }) // {"null":"hello"}
console.log(Object.assign( {
    
     b: "c" },unEnumer ,enumer ));
// {b: "c",null: "hello"}

// 2.合并Symbol 类型,既可以当键也可以当值
 console.log(Object.assign({
    
     a: 'b' }, {
    
     [Symbol('c')]: 'd' },{
    
    'e':Symbol('f')}))
// {a: "b", e: Symbol(f), Symbol(c): "d"}
note
  • Influence relationship between copied data
  • If the copy object is an array, it will be processed according to a dictionary. The array is well understood as a dictionary, such as ['a','b','c'], which will actually automatically assign keys, which is equivalent to {0:'a',1: 'b',2:'c'}, so the processing rules are the same as the dictionary.
  • Handling of value function and assignment function
// 1.影响关系
var obj1 = {
    
     a: 1 },obj2={
    
    b:{
    
    c:1}};
var obj = Object.assign({
    
    }, obj1,obj2);
obj1.a = 2 // 不影响
obj2.b.c = 3 // 影响
console.log(obj,obj1,obj2) // {a: 1,b: {c: 3}}

// 2.处理数组
console.log(Object.assign([1, 2, 3], [4, 5])) // 合并完还是数组 [4, 5, 3]
console.log(Object.assign({
    
    0:1,3:3}, [4, 5])) // 合并完是对象 {0: 4, 1: 5, 3: 3}
console.log(Object.assign( [4, 5],{
    
    0:1,3:3})) // 合并完还是数组 [1, 5, empty, 3]  empty?

// 3.对取值函数处理和赋值函数处理
var obj1={
    
    get foo(){
    
    return "a"}},
obj2={
    
    foo:()=>{
    
    return "a"}}
console.log(obj1) // foo: "a",obj1.foo得到的是函数执行结果,计算属性原理?
console.log(obj2) // foo: ƒ foo(),obj2.foo得到的是函数地址
console.log(Object.assign({
    
    },{
    
    get obj1(){
    
    return "a"}},{
    
    obj2:()=>{
    
    return "a"}})) // {obj1: "a",obj2: ƒ obj2()}
use
  • Add properties to objects, methods
  • Clone objects, combine multiple objects with new syntax
  • Specify default values ​​for attributes
// 1.为对象同时添加(更新)多个属性、方法
var obj = {
    
    title:"标题",dateStamp:"2020/5/22"},
newProp = {
    
    get dateStamp(){
    
     return Date.now()},text:"新属性",fun1(){
    
    return "新方法"}};
console.log(Object.assign(obj, newProp)) // {title: "标题", dateStamp: 1590119249783, text: "新属性", fun1: ƒ}

// 2.克隆
var obj = {
    
    };
var obj1 = {
    
     a: 1 };
Object.defineProperty(obj1, "k", {
    
    
    enumerable: true,
    // value: "hello",
    get() {
    
    
      console.log("获取obj1的k值");
    } // 当使用了getter或setter方法,不允许使用writable和value这两个属性?   
    });
console.log(Object.assign(obj, obj1)); // 获取obj1的k值 {a: 1, k: undefined}
console.log(Object.assign(obj, obj1).k); // 获取obj1的k值 undefined
console.log(obj1.k); // 获取obj1的k值 undefined
// 采用这种方法克隆,只能克隆原始对象自身的值,不能克隆它继承的值(什么意思?)

// 3.为对象指定默认值和属性
const defaultVal = {
    
    
      title: "未定义",
      time: "0"
    };
var obj = {
    
    },
obj1 = {
    
    };
Object.defineProperty(obj1, "title", {
    
    
  enumerable: true,
  // value: "hello",
  get() {
    
    
    console.log("获取obj的title值");
    return "标题"
  }
});
// 注意顺序,先默认值,再配置属性,obj在最后
console.log(Object.assign({
    
    }, defaultVal,obj1,obj));
2. Define the object-Object.defineProperty(obj, prop, descriptor)

Define properties: Object.defineProperty(obj, prop, descriptor)

The properties are defined when the object is created, and the default values ​​of all properties are true; and when the properties added by defineProperty are used, the default values ​​of the properties are all false. When using getter or setter methods, the two attributes of writable and value are not allowed?

obj, the object
prop to be modified , with the modified attribute name
descriptor, the description of the attribute to be modified

configurable, whether the attribute is configurable. The meaning of configurable includes: whether the attribute can be deleted (delete), whether the writable, enumerable, and configurable attributes of the attribute can be modified. After changing to false, the modification cannot be deleted (irreversible). Default true

enumerable, whether the attribute is enumerable. The enumerable meaning includes: whether it can be traversed through for...in, whether the property name can be obtained through the Object.keys() method, if it is changed to false, it will not be traversed when for in, but it is still accessible using "." . Default true

Writable, whether it is writable, change to false, and the current attribute becomes read-only. . Default true

value, the default value of the attribute.

set, the attribute rewriter (so called for now). Once the attribute is reassigned, this method is automatically called.

get, the reader of the attribute (so called for now). Once the property is accessed and read, this method is automatically called.

3. New data type-Symbol

Symbol is a new feature introduced by the ES6 specification, and its function is similar to an ID that identifies uniqueness.

definition
    let s1 = Symbol();
    let s2 = Symbol("another symbol"); // 传入描述信息 可以是任何可以被转型成字符串的值,如:字符串、数字、对象、数组等
    let s3 = Symbol();
    console.log(s1,s2,s3)
    console.log(typeof s1); // 'symbol'
    console.log(s1===s2,s1===s3); // false - 每个Symbol实例都是唯一的。
application
  • Since the Symbol type key cannot be enumerated by Object.keys() or for...in, it is not included in the object's own property names, so it can be used for external operations and access The attribute of is defined by Symbol as the key (unique) of the object;
  • Because of this feature, when using JSON.stringify() to convert an object into a JSON string, the Symbol attribute will also be excluded
  • No need to think about the content of the value
  • High security
  • Multi-module sharing unique
	const NAME = Symbol("it`s const key");
    const AGE = Symbol("it`s const key");
    let obj = {
    
    [NAME]: "默认名称"};
    obj[AGE] = "赋值年龄";
    // 访问
    console.log(obj[NAME],obj[AGE]) // 默认名称, 赋值年龄
    // 获取所有1
    console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(it`s const key), Symbol(it`s const key)]
    // 获取所有2
    console.log(Reflect.ownKeys(obj)); // [Symbol(it`s const key), Symbol(it`s const key)]

    // 定义常量不用再去想值的内容了
    const id = Symbol(); // id - 唯一

	// 注册全局Symbol,实现多模块共享唯一Symbol
    let s1 = Symbol.for("global_symbol_1"); //注册一个全局Symbol
    let s2 = Symbol.for("global_symbol_1"); //获取全局Symbol,注意描述一直才行
    let s3 = Symbol.for("global_symbol_3");
    console.log(s1 === s2); // true
    console.log(s1 === s3); // false

To be continued...

Guess you like

Origin blog.csdn.net/GeniusXYT/article/details/106274219