ES6中的Object
一、数据结构的变化
1、写法简洁(构造函数不可使用)
let name = '小白'; let color = "白色"; const dog1 = {name,color,method() { return 'demo'; }}; //等价于 const dog2 = { name: name, color: color, method: function(){ return 'demo'; } }; const obj = { F() { this.foo = 'bar'; console.log("this is "+foo); } }; //报错 obj.F is not a constructor new obj.F();
2、新增属性名表达式(不能和简洁表示法一起使用)
let name = "dog"; let dog = "我是一只小狗狗"; const obj = { [name]: "小白", ['sa'+'y']: "hello", ['h'+'ello'](){ return 'h1'; }, // [name] 错误的写法 name }; console.dir(obj); //{dog:"小白", hello: f(), name:'dog', say: "hello"}
· 3、方法的name属性
(1)一般情况下,方法的name属性返回函数名;
(2)如果是使用get和set 的话,则是该方法的属性的描述对象的get和set属性上面
(3)使用bind() 创建的函数,返回bound加上原函数的名字
(4)如果是使用Symbol值来定义方法名的话,那么返回的是Symbol只的描述
let s = Symbol('person'); const person = { name:'小白', say() { console.log('hello! My name is '+this.name); }, set show(info){ this.name = info; }, get show(){ return 'show '+ this.name; }, [s]() { console.log("Symbol定义的函数"); } } //1、一般情况下,方法的name属性返回函数名 console.log(person.say.name); //say //2、如果是使用get和set 的话,则是该方法的属性的描述对象的get和set属性上面 const desciptor = Reflect.getOwnPropertyDescriptor(person, 'show'); console.log(desciptor.set.name); //set show console.log(desciptor.get.name); //get show //3、使用bind() 创建的函数,返回bound加上原函数的名字 const p = {name: 'p'}; console.log(person.say.bind(p).name); //bound say //4、如果是使用Symbol值来定义方法名的话,那么返回的是Symbol只的描述 console.log(person[s].name); //[person]
4.属性的可枚举行和遍历
(1)可枚举性
目的:为了规避for....in....对内部属性和方法的遍历(尽量使用 Object.keys() 来替换 for....in.......)
使用:目前有四个操作会忽略enumerable为false 的属性
----for......in...... : 自身和继承的 可枚举属性
----Object.keys() : 自身 可枚举属性
----JSON.stringify() : 自身 可枚举属性
----Object.assign() : 自身 可枚举属性
const person = { name:'小白', say() { console.log('hello! My name is '+this.name); }, } Reflect.defineProperty(person,'age',{ value: 111, writeable: true, configurable: true, enumerable: false }); console.log(person.age); //111 //属性age没有被遍历到 for(item in person){ console.dir(item); //name say } console.dir(Object.keys(person)); //['name','say']
(2)属性的遍历
----for......in...... : 自身和继承的 可枚举属性
----Object.keys(obj) : 自身 可枚举属性
-----Object.getOwnPropertyNames(obj) : 自身所有的属性
-----Object.getOwnPropertySymbols(obj) : 自身的所有Symbol属性
-----Reflect.ownKeys(obj) : 自身的所有属性
5、Object 的创建方法
(1)Object.create()
注:创建一个空的对象 : Object.create(null) 和 {} : 其中, Object.create(null) 不创建prototype,会“更空”。

浙公网安备 33010602011771号