4

#yyds干货盘点#重新梳理箭头函数的this

 1 year ago
source link: https://blog.51cto.com/u_11365839/5446142
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点#重新梳理箭头函数的this

原创

尼羲 2022-07-06 09:20:44 博主文章分类:技术扯淡 ©著作权

文章标签 严格模式 构造函数 全局函数 文章分类 JavaScript 前端开发 yyds干货盘点 阅读数162

记得之前分享过this的用法,是关于普通函数、构造函数的this,今天主要分享ES6箭头函数的this。先看普通函数下的this。

普通函数下的this:

  • 在普通函数中的this总是代表它的直接调用者,在默认情况下,this指的是window,
  • 在严格模式下,没有直接调用者的函数中的this是 undefined使用
  • call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象

箭头函数中的this:

  • 箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),
  • 而不是执行时的对象, 定义它的时候,可能环境是window,也有可能是其他的。
function test() {
console.log(this);
}
test(); //window

test是一个全局函数,也就是挂载在window对象下的 test()等价于window.test();

var obj = {
func: function () {
console.log(this);
setTimeout(function () {
console.log(this);
},0);
}
}
obj.func();
// obj,此时的this是obj对象
// window

func的宿主环境是obj,所以func里面的this是obj。 定时器中的函数,由于没有默认的宿主对象,所以this指向window 严格模式下的this:

function test() {
'use strict';
console.log(this);
}
test();
//undefined

在严格模式下,没有直接调用者的函数中的this是 undefined

"use strict";
var obj={
say:function(){
console.log(this);
}
};
obj.say();
//obj

有直接调用者的this是它的调用者

var obj = {
say: function () {
setTimeout(() => {
console.log(this);
});
}
}
obj.say();
// obj

此时的 this继承自obj, 指的是定义它的对象obj, 而不是 window

var obj = {
say: function () {
var f1 = () => {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
})
}
f1();
}
}
obj.say()

因为f1定义时所处的函数 中的 this是指的 obj, setTimeout中的箭头函数this继承自f1,所以不管有多层嵌套,都是 obj

var obj = {
say: function () {
var f1 = function () {
console.log(this);
setTimeout(() => {
console.log(this);
})
};
f1();
}
}
obj.say()
// window, f1调用时,没有宿主对象,默认是window
// window

箭头函数没有this的绑定,必须通过查找作用链来决定其值。如果箭头函数被非箭头函数包含,则this绑定的是最近以层的非箭头函数的this;否则。this的值会被设置为undefined。 箭头函数在定义的时候它所处的环境相当于是window, 所以在箭头函数内部的this函数window。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK