ES6 objects
Objects minimalist expression
In the main application object properties and methods
In use, a good grasp of the following rules, namely variable expression attribute name, attribute value corresponding to the variable value.
Here variable is declared in advance, assignment.
var hello = 'hello world'
const test = {hello}
console.log(test)
// {hello: "hello world"}
Shorthand method within the object, such an approach is common vue it!
const o = {
method() {
return "Hello!";
}
};
// 等同于
const o = {
method: function() {
return "Hello!";
}
};
scenes to be used
Function return value
function getPoint() {
const x = 1;
const y = 10;
return {x, y}; // 关键
}
getPoint()
// {x:1, y:10}
function processInput(input) {
return { left, right, top, bottom };
}
const { left, right } = processInput(input);
We often see this written in commonjs module.
let 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 }; // 关键
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear
};
module.exports
Vue wording is common in the wording.
Enumerable object properties and traversal
enumberable
Each object has a property description object (descriptor), to control the behavior of this attribute.
let obj = { foo: 123 };
Object.getOwnPropertyDescriptor(obj, 'foo')
//{
// configurable: true
// enumerable: true
// value: 123
// writable: true
//}
enumerable is the enumerable property, if the property is false, some API operations will ignore the object properties! There are four operating ignores the object itself can not be enumerated attribute:
for...in
Loop: only traverse the object itself and inheritance ++ ++ enumerable properties.Object.keys()
: Returns the object's own enumerable key names of all the properties and does not include inherited;JSON.stringify()
: Only serialized object itself enumerable property.Object.assign()
: Ignore enumerable property is false, only a copy of the object's own enumerable properties.
understanding
Interestingly, JS designed the enumerable attribute ( enumberable
the starting point) is to make certain inherited in the prototype chain property or method can not be traversed, because most of the time we only care about the object's own properties. For example, you traverse an array or any object will not print out a length and a head String and other big ticket.
Related API
Object.getOwnPropertyDescriptor(obj, 'foo')
: Returns the object descriptor objecto.propertyIsEnumerable('a');
: Properties of an object is enumerableObject.defineProperty(o, "a", {...属性描述符});
, Define or modify a property on the object. It is noted that the attribute descriptor is default value defined Boolean to false!Object.getOwnPropertyNames(obj)
Traversing all the properties of the object itself, it returns an array of keys, including non-enumerable properties.