zl程序教程

您现在的位置是:首页 >  其他

当前栏目

ES6 从入门到精通 # 06:箭头函数 this 指向和注意事项

2023-03-14 22:57:38 时间

说明

ES6 从入门到精通系列(全23讲)学习笔记。



箭头函数 this 指向


es5 中的 this 指向:取决于调用该函数的上下文对象


箭头函数没有 this 指向。箭头函数内部 this 值只能通过查找作用域链来确定。

例子:

let DocHandle = {
    id: "kaimo313",
    init: function() {
        document.addEventListener("click", function(event) {
            this.doSomeThings(event.type);
        }, false);
    },
    doSomeThings: function(type) {
        console.log(`事件类型:${type}, 当前的id:${this.id}`);
    }
}
DocHandle.init();


点击文档报错:this.doSomeThings is not a function

0dd3f61b798943fdb5aee8cd5a557964.png


说明 this 指向有问题,我们可以打印一下,我们发现这个 this 指向了 document 了:


ed637a0a11b848e785acff93c167cb77.png

es5 处理方式:使用 bind 改变 this 指向。

let DocHandle = {
    id: "kaimo313",
    init: function() {
        document.addEventListener("click", function(event) {
            console.log(this);
            this.doSomeThings(event.type);
        }.bind(this), false);
    },
    doSomeThings: function(type) {
        console.log(`事件类型:${type}, 当前的id:${this.id}`);
    }
}
DocHandle.init();


da5a86e2382f4fa384804f3817adf0e7.png

es6 的处理方式:

d28929a1d86d4e3ab304d7504ffe750e.png


这里我们不能包 init 改成箭头函数,不然 this 会指向 window:因为箭头函数内部 this 值只能通过查找作用域链来确定。

ac9d969a043441a3bd790a9a2b9f7a8d.png



注意事项


1、使用箭头函数后,函数内部没有 arguments。

let getVal = (a, b) => {
    console.log(arguments);
    return a + b;
}
getVal()


因为这里的 this 指向了 window。

91b6811ce0524c4ab911c131b1893cdc.png


2、箭头函数不能使用 new 关键字来实例化对象。

function 函数也是一个对象,但是箭头函数不是一个对象,它其实就是一个语法糖。

let Kaimo313 = function() {};
let k313 = new Kaimo313();
console.log(k313);

let Kaimo = () => {};
let k = new Kaimo();
console.log(k);

03f4bf02428241e4bbc7f90c37930d16.png

87afe18df30542c0959a0ec9b5e69d87.png


所以,只有 Normal 类型的函数(也就是用 function 关键字构造的函数)是可作为构造器使用的,其他类型的函数(箭头函数、方法简写,generator)都无法使用构造器,也就是说,不能用 new 操作符调用。


每个函数创建的定义都归结为 FunctionCreate EcmaScript 规范中的定义。


e2acaccfb17a4e9781a0520e4a1fed34.png