Object.defineproperty () defines attributes

You can create attributes for an Object with Object.defineProperty(), as shown below

let person = {};
Object.defineProperty(person,'name', {value: 'jack'.writable:false // Whether it can be changed, the default is false
    configurable:false.// Whether it can be deleted
    enumerable:false // Whether it can be traversed
})
Object.keys(person).forEach(function(key) {
    console.log(key); // Can't get a value
})
delete person.name; // Attributes cannot be deleted
person.name="White";
console.log(person); // Because the writable above is false, the output value is small white
Copy the code

In addition, set and GET methods are provided

let person = {};
let temp = null;
Object.defineProperty(person, 'name', {
    get: function() {
        return temp + 'You know what? ';
    },
    set: function(val) {
        temp = val + 'who';
    }
})
person.name = "White";
console.log(person.name); // Do you know who the output is?
Copy the code

Object.preventextensions () disables extension

let person = {};
Object.preventExtensions(persion);
person.name="White";
console.log(person.name); //undefined
Copy the code

Object.seal() creates a sealed Object

Object.freeze() creates a frozen Object, which actually calls Object.seal() on an existing Object and marks all existing properties as writable: false so that their values cannot be changed

Object.keys()

The object.keys () method returns an array of the given Object’s own enumerable properties.

var person = {
    name:'xiaowang'.age:18.gender:'male'
}
Object.keys(person).forEach(function(key) {
    console.log(key);  //name age gender
})
Copy the code
var person = {
    name:'xiaowang'.age:18.gender:'male'
}
Object.keys(person).map(function(key,value) {
    console.log(key + ':' + value);
})
Copy the code

The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

const target = { a: 1.b: 2 };
const source = { b: 4.c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
Copy the code