ES6 - 箭头函数与对象的拓展

72 阅读2分钟

箭头函数

this指向定义时所在对象,而不是调用时所在对象

箭头函数没有自己的this,只能沿着作用域链往上找

不可以当作构造函数

箭头函数中没有arguments对象

但是可以使用扩展运算符

let foo = (...args) =>{
    console.log(args)
}

foo(1,2,3)

对象的拓展

属性简介的表示法

对象中的key和value(变量)如果是一样的,那么value可以省略

属性名表达式

默认对象的属性只能是字符串

let name = "lee"
let age = 32
let s = "school"
let obj = {
    name,
    age,
    s: 'BeiDa'
}
console.log(obj);          // {name: 'lee', age: 32, s: 'BeiDa'}

将对象的属性加"[]",对象的key是一个变量

let name = "lee"
let age = 32
let s = "school"
let obj = {
    name,
    age,
    [s]: 'BeiDa'
}
console.log(obj);           // {name: 'lee', age: 32, school: 'BeiDa'}

对象中的方法也可以简写

let name = "lee"
let age = 32
let s = "school"
let obj = {
    name,
    age,
    [s]: 'BeiDa',
    //study: function(){
    //
    //},
    // 方法的简写
    study(){
    
    }
}
console.log(obj);

Object.is()

判断两个值是否严格相等,相当于严格相等 "==="

但是它同严格相等的区别是:判断NaN是否等于NaN

console.log(NaN === NaN);            // false
console.log(Object.is(NaN,NaN));     // true

对象的拓展运算符与Object.assign()实现对象的复制

Object.assign(y,x)中如果y和x有相同的属性,那么x的属性会覆盖y的属性

// 对象的拓展
let x = {
    a: 3,
    b: 4
}

let y = {...x}
console.log(y);        // {a: 3, b: 4}

// 合并对象
let x = {
    a: 3,
    b: 4
}

let y = {}
Object.assign(y,x)   
console.log(y);      // {a: 3, b: 4}

in

判断当前对象是否包含某个属性

let x = {
    a: 3,
    b: 4
}
console.log('a' in x);   // true

in用在数组中判断某个下标是否有值

// arr中下标为3是否有值
let arr = [1,2,3]
console.log(3 in arr);    // false

对象的遍历方式

1.for ... in

let obj = {
    name: 'lee',
    age: 18,
    school: 'BeiDa'
}

for(let key in obj){
    console.log(key,obj[key]);  // name lee; age 18 ;school BeiDa
}

2.Object.keys()

let obj = {
    name: 'lee',
    age: 18,
    school: 'BeiDa'
}

Object.keys(obj).forEach(key => {
    console.log(key,obj[key]);
})

3.Object.getOwnPropertyNames()

let obj = {
    name: 'lee',
    age: 18,
    school: 'BeiDa'
}

Object.getOwnPropertyNames(obj).forEach(key=>{
    console.log(key,obj[key]);
})

4.Reflect.ownKeys()

let obj = {
    name: 'lee',
    age: 18,
    school: 'BeiDa'
}

Reflect.ownKeys(obj).forEach(key=>{
    console.log(key,obj[key]);
})