对象扩展:
1.简洁属性:ES6允许直接写入变量和函数,作为对象的属性和方法
2.属性名表达式
3.name属性 返回函数名
4.Object.js()类似于===
5.Object.assign()用于对象的合并(拷贝),将源对象(source)的所有可枚举属性,复制到目标对象(target)
由于undefined和null无法转换成对象,放在第一个参数会报错,其他位置会跳过
6.属性遍历:
(1)for...in循环遍历对象自身和继承的可枚举属性
(2)Object.keys()遍历自身可枚举属性
(3)Object.getOwnPropertyNames()遍历自身可枚举和不可枚举属性不包含Symbol
(4)Object.getOwnPropertySymbols()遍历自身所有Symbol属性
(5)Reflect.ownKeys()遍历自身所有属性
7.__proto__属性:Object.setPrototypeOf()与Object.getPrototypeOf(obj)
8.Object.keys() Object.values() Object.entries()
<script>
//1.简洁属性
var name='Tim';
var age=12;
var obj1={name:name,age:age};
//ES6
var obj2={name,age}
console.log(obj1,obj2)//{name:Tim,age:12} {name:Tim,age:12}
var obj3={name:name,age:age,show:function(){
console.log('hello')
}}
//ES6
var obj4={name,age,show(){
console.log('hello')
}}
//2.属性名表达式
var name='show'
var obj5={
show2:'hello',
[name]:'world'
}
console.log(obj5);//{show2:'hello',show:'world'}
var obj6={
name,
age,
hello(){
console.log('hello');
}
}
//3.name属性
var person={
sayName(){
console.log(this.name);
}
}
console.log(person.sayName.name);//sayName
//4.Object.js()
console.log({}=={});//false
console.log({}==={});//false
console.log([]==[]);//false
console.log([]===[]);//false
console.log(Object.is({},{}));//false
console.log(Object.is([],[]));//false
//Object.is()和===的区别
console.log(-0===+0);//true
console.log(NaN===NaN);//false
console.log(Object.is(-0,+0));//false
console.log(Object.is(NaN,NaN));//true
//5.Object.assign()
var target={
a:1
};
var source1={
a:2,
b:2
};
var source2={
c:3
};
//合并属性
Object.assign(target,source1,source2);
console.log(target);//相同覆盖{a: 2, b: 2, c: 3}
var s3=Object.assign({},source1,source2);//常见用法:值拷贝
console.log(s3);//{a: 2, b: 2, c: 3}
//6.属性遍历
var obj7={
a:1,
b:2,
c:3,
[Symbol()]:0
}
console.log(Object.keys(obj7));//['a', 'b', 'c']
console.log(Object.getOwnPropertyNames(obj7));//['a', 'b', 'c']
console.log(Object.getOwnPropertySymbols(obj7));//[Symbol()]
console.log(Reflect.ownKeys(obj7));//['a','b','c',Symbol()]
//7.__proto__属性
var proto={
y:2
}
var obj8={
x:10
}
console.log(Object.getPrototypeOf(obj8));//{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
//8.Object.keys() Object.values() Object.entries()
var obj9={
x:10,
y:20
}
console.log(Object.keys(obj9));//['x','y']
console.log(Object.values(obj9));//[10,20]
console.log(Object.entries(obj9));//[Array(2),Array(2)]
</script>