所谓的没有 this,不是箭头函数中没有 this 这个变量,而是箭头函数不绑定自己的 this,它们会捕获其所在上下文的 this 值,作为自己的 this 值。这对于回调函数特别有用,可以避免传统函数中常见的 this 指向问题。例如,在对象方法中使用箭头函数可以确保 this 保持一致。
习题练习
第一题
var name =222
var a ={
name:111,
say:function(){
console.log(this.name)
}
}
var fun = a.say
fun()//是 fun.call(window)的简写 //222
a.say()// a.say.call(a)//111
var b ={
name:333,
say:function(fn){
fn()//fn.call(window)的简写 //222
}
}
b.say(a.say)
b.say=a.say
b.say()//b.say.call(b)//33
第二题
var x =11;
var obj={
x:22,
say:()=>{
console.log(this.x);//
}
}
obj.say()//11
//箭头函数本身没有this,它的this是继承自父执行上下文的this,比如这里的箭头函数this.x,箭头函数本身域say平级,类似于Key:value的形式,也就是箭头函数本身所处的环境是obj, 所以它的this指向obj外侧的window,故输出 11
第三题
globalThis.a = 100;
function fn() {
return {
a: 200,
m: function() {
console.log(this.a);
},
n: ()=>{
console.log(this.a);
},
k: function() {
return function() {
console.log(this.a)
}
}
};
}
const fn0 = fn();
fn0.m(); // 输出 200,this 指向 {a, m, n}
fn0.n(); // 输出 100,this 指向 globalThis
fn0.k()(); // 输出 100, this 指向 globalThis
const context = {a: 300}
const fn1 = fn.call(context); // 改变箭头函数 this 指向
fn1.m(); // 输出 200,this 指向 {a, m, n}
fn1.n(); // 输出 300,this 指向 context
fn1.k().call(context); // 输出 300,this 指向 context
第四题
var name = 'window'
const person1 = {
name: 'person1',
foo1: function() {
console.log(this.name)
},
foo2: () => {
console.log(this.name)
},
foo3: function() {
return function() {
console.log(this.name)
}
}
}
const person2 = {
name: 'person2'
}
person1.foo1() // person1
person1.foo1.call(person2) // person2
person1.foo2() // window
person1.foo2.call(person2) // window
person1.foo3()() // window
person1.foo3.call(person2)() // window
第五题
let length = 10;
function fn() {
return this.length + 1
}
const obj = {
length: 5,
test1: function() {
return fn()
}
}
obj.test2 = fn;
console.log(obj.test1()); // window 的窗口数 (window.length 是页面子窗口数量)
console.log(fn() === obj.test2()) // false