一句话快速理解JS中this的指向

ps: 如果有任何问题可以评论留言,我看到后会及时解答,评论或关注,您的鼓励是我分享的最大动力

      转载请注明出处:https://blog.csdn.net/qq_40938301/article/details/88077375

1、普通的函数

this 的指向是在函数执行时才确定的

this 指向的是调用this所在函数的这个对象

eg:

var xm = {
	name: "小明",
	gender: "男",
	age: "22",
	say:function(){
		console.log("我叫"+this.name)//我叫小明
    }
}

xm.say();

2、es6中的箭头函数

箭头函数内部的this指向与上下文关联

可以直接视作 => 非函数来理解

eg:

var xm = {
	name: "小明",
	gender: "男",
	age: "22",
	say:function(){
		var a = () => {
			console.log("我叫"+this.name)
        }
		a();
    }
}

xm.say();

3、js中 call 、 apply 和 bind 可以更改this的指向

具体可见我的另一篇博文 https://blog.csdn.net/qq_40938301/article/details/88077745

发布了57 篇原创文章 · 获赞 12 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_40938301/article/details/88077375