TypechoJoeTheme

Lonhaiy的个人博客

登录
用户名
密码

Lonhaiy

如果结果不如你所愿,就在尘埃落定前奋力一搏
标签搜索
JS

ES6 箭头函数和this

2022-08-26
/
0 评论
/
512 阅读
/
正在检测是否收录...
08/26

ES6 箭头函数和this

了解更多请访问https://www.bilibili.com/video/BV1QE411q7C2

一.箭头函数

1、ES6 新增了一个使用(=>)箭头符号定义函数的语法特性

// 传统函数代码写法
let fn = function(name){
    return name;
}
//ES6箭头函数写法
let fn = name => name;
console.log(fn('Mr.Lon'));

从例子我们可以看出,省略了function,花括号‘{}’用‘=>’代替了。这种写法更简洁了。

2、箭头函数也可以传递两个或以上的参数,并实现运算后返回

let fn = (x , y) => x + y;
console.log(fn(10,20));

//翻译成函数代码为
let fn = function(x,y){
    return x + y;
}

3、如果你定义的函数,并不需要传递参数,可以用()括号方式直接返回

let fn = () => 'Mr.Lon';
console.log(fn());

//翻译成函数代码为
let fn = function(){
    return 'Mr.Lon';
}

4、如果函数体需要更复杂的操作,可以将箭头符号右边使用传统函数体

let fn = (x , y)=>{
    return x + y;
}
console.log(fn(10 , 20))

5、如果箭头符号右边是对象,返回的是对象,则需要用圆括号包含着

let fn = name => ({name : name , age : 100})
console.log(fn('Mr.Lon').name)

//翻译成函数代码为
let fn = function(name){
    return{
        name : name,
        age : 100
    }
}

6、自我立即执行函数,也可以使用箭头符号来创建,具体如下:

((name) => {
    console.log(name);
})('Mr.Lon')

//翻译成函数代码为
(function(name){
    console.log(name);
})('Mr.Lon')

二.绑定 this

1、ES6 之前有一个比较头疼的问题,就是 this 指向的问题,比如下面例子

let obj = {
    name : 'Mr.Lon',
    age : 100,
    fn : function(){
        setTimeout(function(){
            console.log(this.name + ',' + this.age)
        }, 500);
    }
}
obj.fn()
上面的例子比较典型,this 全局指向 window,在某个对象内部指向当前对象
当 obj 对象下包含了类似 setTimeout 函数内部,这时 this 指向就出现问题了
Web 环境下,它指向了 Window,而 node 环境下它指向 setTimeout
所以,我们通俗的做法,就是将 this 在 setTimeout 外部进行赋值保存
let obj = {
    name : 'Mr.Lon',
    age : 100,
    fn : function(){
        /* 
        在setTimeout里面,如果我们直接写this的话,这个this是指向window的。
        因此我们需要在setTimeout函数之前先保存that = this;
        */
        let that = this;
        setTimeout(function(){
            console.log(that.name + ',' + that.age)
        }, 500);
    }
}
obj.fn()
箭头函数的出现,彻底解决了 this 在内部指向的问题,直接指向我们所需要;
因为,箭头函数中的 this 是最外层定义的函数绑定,不受内部影响;
let obj = {
    name : 'Mr.Lee',
    age : 100,
    fn : function(){
       setTimeout(() => {
           console.log(this.name + ',' + this.age)
       }, 500);
    }
}
obj.fn()

三、箭头扩展

1、箭头也支持一些内置函数的使用,比如 sort()排序;

let arr = [3,1,2].sort((a,b) => a - b);
console.log(arr)

//翻译后的代码为:
let arr = [3,1,2].sort(function(a,b){
    return a - b;
});

2、箭头函数不支持 arguments 绑定,请直接使用...other 模式(rest 运算符);

//下面这种写法不支持
let fn = (x , y) =>{
    return arguments[0] + arguments[1]
}

//不确定参数,使用...
let fn = (...other) => {
    return other[0] + other[1]
}
console.log(fn(10,20))
赞(0)
版权属于:

Lonhaiy的个人博客

本文链接:

http://www.lonhaiy.com/index.php/archives/22/(转载时请注明本文出处及文章链接)

评论 (0)
Lonhaiy
如果结果不如你所愿,就在尘埃落定前奋力一搏
20 文章数
5,716 评论量

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月