The first half of object extension of ES6

Brief representation of attributes

var foo = 'bar';
var baz = {foo};
console.log(baz);       //{ foo: 'bar' }


function f(x, y) {
    return {x, y};
}
console.log(f(1, 2));   //{ x: 1, y: 2 }


var o = {
    method() {
        return 'Hello';
    }
};
//Equivalent to
var o = {
    method: function () {
        return 'Hello';
    }
};
console.log(o.method());        //Hello

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

console.log(getPoint());    //{ x: 1, y: 10 }


# CommJS module output variables are very suitable for introduction
var ms = {};

function getItem(key) {
    return key in ms ? ms[key] : null
}

function setItem(key, value) {
    ms[key] = value;
}

function clear() {
    ms = {}
}


module.exports = {getItem,setItem, clear};
//Equivalent to
module.exports = {
    getItem:getItem(),
    setItem: setItem(),
    clear: clear()
}
ps: The assignor and accessor of the above attributes adopt the method of attribute shorthand

Property name expression

There are two ways for JS language to define the properties of objects.
1. Defining properties with identifiers (ES5)
2. Use expression as property name (ES6)

// ES5 identifier as attribute name 
var obj = {
    foo:true,
    abc: 123
}

// ES6 expression as property name

let propKey = 'foo';
let obj = {
    [propKey]: true,
    ['a'+'bc']:123
}

let lastWord = 'last word';
var a = {
    'first word':'hello',
    [lastWord]:'world'
}

console.log(a['first word']);
console.log(a[lastWord]);
console.log(a['last word']);

Note: property name expressions and profile representations cannot be used at the same time

var foo = 'bar';
var bar = 'abc';
var baz = {[foo]};  //  A blunder on the precipice

var foo = 'bar';
var baz = {[foo]: 'abc'};  // Correct writing

name attribute of method

var person = {
    sayName(){
        console.log(this.name);
    },
    get firstName(){
        return 'Loyal';
    }
}

console.log(person.sayName.name);       //Pro test: sayName

console.log(person.firstName.name);     //Pro test:undefined  The book answers are: get firstName

Note: there are two special cases: 1. For the Function created by bind method, name returns "bound" + the original Function name; 2. For the Function created by Function constructor, name attribute returns "anonymous"

console.log((new Function()).name);     //anonymous
var doSomething = function () {
        // ....
}
console.log(doSomething.bind().name);   //bound doSomething

Object.is() is used to compare whether two values are strictly equal. It is basically consistent with the satisfaction of strict comparison operators

console.log(Object.is('foo', 'foo'));       //true
console.log(Object.is({}, {}));             //false

# Slightly different
console.log(+0 === -0);                     //true
console.log(NaN === NaN);                   //false

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

ps: ES5 The following code can be used to implement theObject.is function
Object.defineProperty(Object, 'is', {
    value: function(x,y){
       if(x === y) {
           return x !== 0 || 1/x === 1/y;
       }
        return x !== x && y !== y;
    },
    configurable: true,
    enumerable: false,
    writable: true
})

Object.assign() is used to copy all enumerable properties of the source object to the target object. At least two objects are required as parameters. The first parameter is the target object, and the next parameter is the source object. As long as one is not an object, a TypeError error will be thrown

var target = {a: 11};
var source1 = {b:2};
var source2 = {c:3};
console.log(Object.assign(target, source1, source2));   //{ a: 11, b: 2, c: 3 }

# Note that if the target object and the source object have properties with the same name, or multiple source objects have properties with the same name, the following properties will overwrite the previous ones
var target = {a: 11, b:3};
var source1 = {b:2};
var source2 = {c:3};
console.log(Object.assign(target, source1, source2));   //{ a: 11, b: 2, c: 3 }


# Nested objects, Object.assign is handled by replacing rather than adding
var target = {a:{b:{c:5,d:6}} };
var source1 = {a:{b:'hello'}};
console.log(Object.assign(target, source1));   //{ a: { b: 'hello' } }

# Handle arrays, but treat them as objects and replace them
console.log(Object.assign([1, 2, 3], [4, 5]));  //[ 4, 5, 3 ]
  • Add properties to objects
Class Point{
 constructor(x,y){
     Object.assign(this, {x,y})
 }
}
  • Add method to object
Object.assign(SomeClass.prototype, {
  someMethod(arg1,arf2){

  },
  anotherMethod(){

  }
})
//Equivalent to

SomeClass.prototype.someMethod = function (arg1,arf2){
  //...
}
SomeClass.prototype.anotherMethod = function () {
  //...
}
  • Clone object
function clone(origin){
    return Object.assign({}, origin);
}

By copying the academician object to a control object, we get the clone of the potential object
You can only clone the value of the original object, not the inherited value. To keep the inheritance chain, try the following code

function clone(origin) {
    let originProto = Object.getPrototypeOf(origin);
    return Object.assign(Object.create(originProto), origin);
}
  • Merge multiple objects
const merge = (target,...source) => Object.assign(target,...source);
const merge = (...source) => Object.assign({}, ...source);
  • Specify default values for properties
const DEFAUlTS = {
    logLEvel: 0,
    ouputFormat: 'html'
}
function processContent(options) {
    let options = Object.assign({}, DEFAUlTS, options);
}

Tags: Attribute

Posted on Sun, 03 May 2020 04:30:07 -0700 by mimintweak