JavaScript 学习-8.JavaScript 箭头函数的使用-编程思维

前言

ES6 中引入了箭头函数() =>。箭头函数不需要使用function关键字,允许我们编写更短的函数.

箭头函数

之前使用function 定义函数

fun1 = function() {
  return "Hello World!";
}
console.log(fun1()); // Hello World!

使用箭头函数() =>格式

fun2 = () => {
  return "Hello World!";
}
console.log(fun2()); // Hello World!

只有一条语句

当只有一条语句的时候,并且该语句返回一个值,我们去掉大括号和 return 关键字

fun3 = () => "Hello World!";
console.log(fun3()); // Hello World!

或者也可以返回一个表达式

a = 'hello';
b = 'world!'
fun4 = () => a+b;
console.log(fun4()); // helloworld!

箭头函数传参

当需要传参数的时候,把参数放到圆括号

fun5 = (a, b) => a+b;
console.log(fun5('hello', 'world')); // helloworld

当只有一个参数的时候,圆括号也能省略

fun6 = x => x+'world';
console.log(fun6('hello')); // helloworld

参数带默认值

当参数带默认值的时候,调用函数可以不用传参

fun7 = (x='hello') => x+'world';
console.log(fun7()); // helloworld
console.log(fun7('yoyo')); // yoyoworld

this的使用

使用箭头函数没有对 this 的绑定。
在常规函数中,关键字 this 表示调用该函数的对象,可以是窗口、文档、按钮或其他任何东西。

对于常规函数,this 表示调用该函数的对象:

// 常规函数:
hello = function() {
  document.getElementById("demo").innerHTML += this;
}

// window 对象调用该函数:
window.addEventListener("load", hello);        // Window

// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello);         // HTMLButtonElement

用了箭头函数,则 this 表示函数的拥有者:

// 箭头函数:
hello = () => {
  document.getElementById("demo").innerHTML += this;
}

// window 对象调用该函数:
window.addEventListener("load", hello);  // Window

// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello);  //Window

对于箭头函数,this 关键字始终表示定义箭头函数的对象。

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/yoyoketang/p/16282965.html