ES6的增强写法

1. ES6的对象属性增强型写法

ES6以前定义一个对象

const name = "zzz";
const age = 18;
const user = {
  name:name,
  age:age
}
console.log(user);

ES6写法

const name = "zzz";
const age = 18;
const user = {
	name,age
}
console.log(user);

2 ES6对象的函数增强型写法

ES6之前对象内定义函数

const obj = {
  run:function(){
     console.log("奔跑");
  }
}

ES6写法

const obj = {
  run(){
     console.log("奔跑");
  }
}

3. 箭头函数

传统定义函数的方式

  const aaa = function (param) {
      
  }

对象字面量中定义函数

const obj = {
    bbb (param) {  },
}

ES6中的箭头函数

//const ccc = (参数列表) => {}
  const ccc = () => {}

4. 箭头函数的参数和返回值

4.1 参数问题

1.放入两个参数

const sum = (num1,num2) => {
    return num1 + num2 
}

2.放入一个参数,()可以省略

const power = num => {
  return num * num
}

4.2 函数内部

1.函数中代码块中有多行代码

const test = () =>{
  console.log("hello zzz")
  console.log("hello vue")
}

2.函数代码块中只有一行代码,可以省略return

// const mul = (num1,num2) => {
//   return num1 * num2
// }
const mul = (num1,num2) => num1* num2
// const log = () => {
//   console.log("log")
// }
const log = () => console.log("log")

4.3 箭头函数的this使用

什么时候使用箭头函数

setTimeout(function () {
	console.log(this)
} , 1000);
setTimeout(() => {
	console.log(this)//这里this找的是window的this
}, 1000);

结论:箭头函数没有this,这里this引用的是最近作用域(aaa函数里的this)的this。

    const obj = {
      aaa(){
        setTimeout(function () {
          console.log(this)//window
         });
         setTimeout(() => {
          console.log(this)//obj
        });
      }
    }
    obj.aaa()

上述中第一个是window对象的this,第二个箭头函数的this是obj的。

    const obj = {
      aaa() {
        setTimeout(function () {
          setTimeout(function () {
            console.log(this) //window
          })
          setTimeout(() => {
            console.log(this) //window
          })
        })
        setTimeout(() => {
          setTimeout(function () {
            console.log(this) //window
          })
          setTimeout(() => {
            console.log(this) //obj
          })
        })
      }
    }
    obj.aaa()
原文地址:https://www.cnblogs.com/NB01/p/14116949.html