An overview of the

Other data besides String, number, Boolean, NULL, undefined, and symbol are JavaScript objects: arrays, dates, even functions, and so on.

In JavaScript, an object is data with attributes and methods, an unordered collection of data, and a collection of key-value pairs.

The key is the property name, and the value is the property value.

Variable as attribute name

let p1 = 'name'
let obj = { p1: 'never' }   // Attribute name is p1
let obj = { [p1]: 'never' } // Attribute name' name'
Copy the code

Keys (obj) Gets the key of the Object obj

Deleting properties (Delete)

Delete the XXX attribute of obj

Delete obj. XXX or delete obj[' XXX ']

View all properties (View)

View all of its properties

Object.keys(obj)

View self + Common properties

console.dir(obj)

Key is equivalent to obj[‘key’] is not equivalent to obj[key]

Let key = ‘never’

Obj [key] equivalent to obj[‘never’]

Modify or add attributes (change, add)

Direct assignment

let obj = { name:'frank' } // Name is a string
obj.name = 'frank'         // Name is a string
obj['name'] = 'frank'
obj[name] = 'frank'        // Error, because name value is not determined
obj['na'+'me'] = 'frank'
let key = 'name'; obj[key] = 'frank'
let key = 'name'; obj.key = 'frank' // error because obj. Key is equivalent to obj['key']
Copy the code

Batch assignment

Object.assign(obj, { key1: value1, key2: value2, key3: value3 })

Common attributes cannot be modified or added by themselves

let obj = {}, obj2 = {} / / the toString
obj.toString = 'xxx'    // Only obj properties will be changed, obj2.toString will still use the prototype
Copy the code
obj.__proto__.toString = 'xxx'    // __proto_ is not recommended
Object.prototype.toString = 'xxx'
Copy the code

In general, don’t modify a prototype, it can cause a lot of problems

Modifying common Attributes

__proto__ is not recommended:

let obj = {name:'never'}
let obj2 = {name:'more'}
let common = {kind:'human'}
obj.__proto_ = common
obj2.__proto__ = common
Copy the code

It is recommended to specify the prototype using object.create () :

let common = {kind:'human'}
let obj = Object.create(common) // Specify the prototype common for obj
obj.name = 'never'
let obj2 = Object.create(common)
obj2.name = 'more'
Copy the code

The specification recommends specifying it initially and not changing it thereafter.

Determines whether an object contains an attribute

Determine whether an attribute is present (can’t tell whether it’s own or common)

'xxx' in obj === true

Determine whether an attribute is self-contained or common

Obj. HasOwnProperty toString (' ')

Determines whether an attribute is present (although the value is undefined)

'xxx' in obj && obj.xxx === undefined

Note that obj. XXX === undefined does not determine whether ‘XXX’ is a property of obj

Analogy: I have toilet paper, but at home (attribute, but undefined value)

var obj = {}

var obj2 = { x: undefined }

obj.x === undefined // true

obj2.x === undefined // true