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


    说明

    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();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

    在这里插入图片描述

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

    在这里插入图片描述

    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();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    es6 的处理方式:

    在这里插入图片描述

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

    在这里插入图片描述

    注意事项

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

    let getVal = (a, b) => {
    	console.log(arguments);
    	return a + b;
    }
    getVal()
    
    • 1
    • 2
    • 3
    • 4
    • 5

    因为这里的 this 指向了 window。

    在这里插入图片描述

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

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

    let Kaimo313 = function() {};
    let k313 = new Kaimo313();
    console.log(k313);
    
    let Kaimo = () => {};
    let k = new Kaimo();
    console.log(k);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    在这里插入图片描述

    拓展

    未标识为构造函数的内置函数对象不实现 [[Construct]] 内部方法,[[Construct]] 是我们使用 new 或 super 创建新对象时使用的东西,只有类型的函数 Normal 才能构造和实现 [[Construct]]

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

    每个函数创建的定义都归结为 FunctionCreate EcmaScript 规范中的定义。
    在这里插入图片描述

    具体可以参考【捣鼓】TypeError: “x” is not a constructor

  • 相关阅读:
    智能工业通信解决方案!钡铼BL124实现Modbus转Ethernet/IP互联!
    day47:C++ day7,异常处理、using的第三种用法、类型转换、lambda表达式、STL标准模板库
    19 Python的math模块
    【PWN · heap | Off-By-One】Asis CTF 2016 b00ks
    (三)Linux 用户和权限
    @Transactional注解在类上还是接口上使用,哪种方式更好?
    盘点Win前端开发下常用的软件
    159_模型_Power BI 地理分析之形状地图
    渗透测试怎么入门?(超详细解读)
    HTML入门篇---01常用标签
  • 原文地址:https://blog.csdn.net/kaimo313/article/details/125857405