前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >箭头函数与this指向探究

箭头函数与this指向探究

作者头像
阿超
发布2022-08-17 21:29:17
4220
发布2022-08-17 21:29:17
举报
文章被收录于专栏:快乐阿超快乐阿超

我有明珠一颗,久被尘劳关锁,一朝尘净光生,照破山河万朵。——柴陵郁禅师

今天研究了下箭头函数与this,发现了一些挺好玩的特性

首先,我们在控制台输入上这段js

代码语言:javascript
复制
var handler = {
    name :'handler',
    init: function() {
    let init1 = function(event) {
        console.log("init1: ", this);
        let init5 = function(){
            console.log("init5: ", this);
        }
        init5();    // init5:  Window {window: Window, self: Window, document: document, name: '', location: Location, …}
    };
    init1()    // init1:  Window {window: Window, self: Window, document: document, name: '', location: Location, …} 
    let init2 = () => console.log("init2: ", this);
    init2.call()    // init2:  {name: 'handler', init: ƒ}
    let init3 = () => {
        let init4 = ()=> console.log("init4: ", this);
        init4()    // init4:  {name: 'handler', init: ƒ}
    }
    init3.apply();
  },
};
handler.init();
image-20211113165351571
image-20211113165351571

可以明显的看到,箭头函数是锁定了this指向的,这里的箭头函数中的this都指向这个handler对象

而使用function声明的函数中的this永远指向外部的window对象

我们再到webpack构建的vue项目中尝试

代码语言:javascript
复制
printThis() {
	console.log("printThis", this);		// VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}

	function print1() {
		console.log("print1: ", this);		// undefined

		function print2() {
			console.log("print2: ", this);		// undefined
			let print3 = () => void console.log("print3: ", this);		// undefined
			print3.apply()
		}
		print2.call();
		let print4 = () => void console.log("print4: ", this);		// undefined
		print4.apply();
	}
	print1.call();

	let print5 = () => {
		console.log("print5: ", this)		// VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
		let print6 = () => console.log("print6: ", this);		// VueComponent {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
		print6.call();
	};
	print5();
}
image-20211113171322127
image-20211113171322127

可以看到这里的箭头函数中的this都为undefined

而使用function声明的函数仍然指向当前Vue组件实例

了解这个特性,能清楚this的具体指向,方便后续前端开发

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档