javascript的箭头函数

javascript的箭头函数

箭头函数的定义

箭头函数(Arrow Function):ES6标准中新增的函数,叫箭头函数的原因是因为它使用了 ’ => ’ 来进行标识

箭头函数的基础语法

  • 通常定义函数的方法有两种

    • 使用function关键字声明函数
    • 使用函数表达式声明函数
  • 箭头函数的定义方法

    • 具名的箭头函数
    var 函数名 = (params1,params2,...) => {
          
          
        //函数体
    }
    
    • 匿名的箭头函数
    (params1,params2,...) => {
          
          
        //函数体
    }
    
function fn1(a, b) {
    
    
    return a + b
}

//不简写

var fn1 = (a,b) =>{
    
    
    return a+b
}

function fn2(a) {
    
    
    return a
}

// 只有一个参数的时候,括号可省略
var fn2 = a =>{
    
    
    return a
}

function fn3() {
    
    
    console.log(1)
}

// 函数体语句只有一句时,{}可省略
var fn3 =  () => console.log(1)

function fn4() {
    
    
    return(1)
}

// 函数体语句只有一句时且为返回语句时,{}和return可省略
var fn4 = () => 1

// 如果返回的是一个对象的话,对象外需要加括号
() => ({
    
    x:1})

箭头函数的特点

  • 箭头函数this为父作用域的this,不是调用时的this,箭头函数的this永远指向其父作用域,任何方法都改变不了,包括call,apply,bind。

bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值。例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj

  • 在对象的方法中,箭头函数的this指向就是父作用域的this指向(即函数作用域中的this指向)
window.name = 'window';
var obj = {
    
    
    name:'obj',
    show_name:function(){
    
    
        console.log(this.name);
    }
}
obj.show_name();//对象方法中的this指向对象

window.name = 'window';
var obj = {
    
    
    name:'obj',
    show_name:()=>{
    
    
        console.log(this.name);
    }
}
obj.show_name();
  • 在计时器中,使用箭头函数可以保留通过构造函数绑定的this指向
// function count(){
    
    
//     this.num = 0
// }
// var a = new count()
// console.log(a.num)

//实现每秒将num的值加一
function count(){
    
    
    this.num = 0;
    // 在计时器中,this指向window对象
    this.timer = setInterval(function add(){
    
    
        this.num++
        console.log(this.num)
    },1000)
}
var b = new count()


function count() {
    
    
    this.num = 0;
    this.timer = setInterval(()=> {
    
    
        this.num++;
        console.log(this.num)
    }, 1000)
}
var b = new count()
  • 在使用箭头函数声明函数时,不能使用new关键字来实例化对象,否则会报错

var b = x => this.name = x
var a = new b
console.log(a.name)

猜你喜欢

转载自blog.csdn.net/w19981225/article/details/108005838