Object characteristics
definition
- Unordered data collection
- Collection of key-value pairs
Key name (attribute name)
- The key name (attribute name) is a string and can contain any characters
- Quotation marks can be omitted. After omitting, only identifiers can be written. If the quotation marks are omitted, the key name is still a string
- All attribute names without [] will automatically become strings. If the value is not a string, it will automatically become a string
- Added [] will be evaluated as a variable (use the variable as the attribute name)
- Object.keys(obj) can get all keys of obj
Hidden properties of objects
- Every object in JS has a hidden attribute (each object is an unawakened Saiyan (__proto__), he can go to Saiyan planet ( the object's common attribute ) to get himself when he needs to be awakened Something needed ( call ))
- This hidden attribute stores the address of an object composed of its common attributes
- This object composed of common properties is called prototype
- In other words, the hidden attribute stores the address of the prototype
1. Two syntaxes for declaring objects
let obj = {
'name': 'frank', 'age': 18 }
let obj = new Object({
'name': 'frank'})
Second, how to delete the attributes of the object
delete obj.xxx 或
delete obj['xxx']
即可删除obj的xxx属性
区分[属性值为undefined] 和 [不含属性名]
[含有属性名,属性值为undefined]
'xxx' in obj && obj.xxx === undefined
[不含属性名]
'xxx' in obj === false
注意obj.xxx === undefined
不能断定'xxx'是否为obj的属性
Three, how to view the properties of the object
查看自身所有属性
Objext.keys(obj)
查看自身+共有属性
console.dir(obj)
或者自己一次用Object.keys打印出onj.__proto__
判断一个属性是自身的还是共有的
obj.hasOwnProperty('toString')
查看属性
中括号语法:obj['key']
点语法:obj.key
坑人语法:obj[key]//变量key值一般不为'key'
优先使用中括号语法,进阶用点语法
name是字符串
obj.name
obj['name']
name是变量
obj[name]
Fourth, how to modify or increase the attributes of the object
•直接赋值
let obj = {
name: 'frank'} // name 是字符串
obj.name = 'frank' // name 是字符串
obj['name'] = 'frank'
obj[name] = 'frank' // 错,因name 值不确定
obj['na'+'me'] = 'frank'
let key = 'name'; obj[key] = 'frank'
let key = 'name'; obj.key = 'frank' // 错
因为 obj.key 等价于 obj['key']
•批量赋值
Object.assign(obj, {
age: 18, gender: 'man'})
无法通过自身修改或增加共有属性(原型)
let.obj = {
}, obj = {
} //共有toString
obj.toString = 'xxx'只会在改obj自身属性
obj2.toString还是在原型上
修改或增加原型上的属性
obj.__proto__.toString = 'xxx' // 不推荐用__proto__
Object.prototype.toString = 'xxx'
一般来说,不要修改原型,会引起很多问题
修改隐藏属性__proto__
·不推荐使用
let obj = {
name: 'frank'}
let obj2 = {
name: 'jack'}
let common = {
kind: 'human'}
obj.__proto__ = common
obj2.__proto__ = common
注:所有 __proto__ 代码都是强烈不推荐写的
·推荐使用Object.create
let obj = Object.create(common)
obhj.name = 'frank'
let obj2 = Object.create(common)
obj2.name = 'jack'
规范大概的意思是,要改就一开始改,不要后来再改
Five, the difference between'name' in obj and obj.hasOwnProperty('name')
'name' in obj
判断一个对象属性或原型里面是否包含某个key,key为字符串
如果一个属性是从原型链上继承来的,in运算符也会返回 true。
obj.hasOwnProperty('name')
所有继承了Object的对象都会继承到hasOwnProperty方法。
这个方法可以用于检测一个对象是否包含特定的固有属性;
和in运算符不同,该方法会忽略掉那些从原型链上继承到的属性。