ES6 中的对象

3.对象

说明:此处主要讲解对象的扩展语法。

3.1 属性简洁表示法

es6 允许直接写入变量和函数,作为对象的属性和方法。

const name ="aaa";
const age = 12;
let obj ={
name:name,// 原来的写法
age:age
}
console.log(obj);
>>> {name: 'aaa', age: 12}

当变量键和值都相同的时候,可以胜率掉相关的值。直接写出对应的名称即可。

const name ="aaa";
const age = 12;
let obj ={
name,
age
}
console.log(obj);// 效果与上述的效果是一样的。
>>> {name: 'aaa', age: 12}

方法也可以简单写,

const name ="aaa";
const age = 12;
let obj ={
name,
age,
sayName(){
console.log(this.name);
}//
/* 原来的写法为:
sayName:function(){
console.log(this.name);
}*/
}
obj.sayName();
>>> aaa

返回值的简化

const name ="aaa";
const age = 12;
function fn(x,y) {
return {x,y}
}
console.log(fn(name,age)) // >>> {x: 'aaa', y: 12}
/* 等价于
return{
x: x,
y: y,
}
*/

属性的赋值器和取值器,事实上也是采用这种写法。

let cart = {
wheel: 4,
set() {
return this.wheel;
},
get(newVal) {
if (newVal < this.wheel) {
throw new Error('轮子太小了');
}
this.wheel = newVal;
}
}
console.log(cart.set()) // 4

3.2 属性名的表达式

const obj = {}; //定义相关的对象
obj.foo = true; // 设置相关的属性
obj['a' + 'bc'] = 123; // 属性名可以是使用表达形式
console.log(obj);
>>> {foo: true, abc: 123}

自定义的形式

let obj = {
foo: true,
['a' + 'bc']: 123,
['f' + 'av']: function () {
return this['a' + 'bc'];
}
}
console.log(obj);//
>>> {foo: true, abc: 123, fav: ƒ()}

3.3 扩展对象的方法

1.is()比较两值是否相等,函数判断比较严格,===有几种情况比较特殊。

//(1) is()
console.log(NaN === NaN); //False
console.log(+0 === -0); //true
console.log(Object.is(NaN, NaN));//true
console.log(Object.is(+0, -0)); //false

2.assign()

此方法用于对象的合并,对象的新方法,将源对象的所有可枚举属性赋值到目标对象中
//1.Object.assign(target,对象1,对象2)
let target = {};
let obj1 = {
a: 1
};
let obj2 = {
b: 2
};
Object.assign(target,obj1,obj2);
console.log(target);//
>>> {a: 1, b: 2}
// assign的属性拷贝是浅拷贝
let newObj = Object.assign({},obj2);
console.log(newObj);
>>> {b: 2}

posted @   紫青宝剑  阅读(222)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示