类中方法的this输出问题
来源:6-4 this 有几种赋值情况

慕丝1117639
2022-02-24
老师我这里定义了一个类,在类中定义了一个方法say,然后在say中有分别定义了两个方法,都是用来打印this的。
然后我在Person的原型上又定义了talk方法,同样的在talk方法中也定义了两个打印this的方法。
say和talk都是通过实例对象调用的,执行的环境是相同,但是它们的内部函数打印出来的this却不一样,请问这是为什么呢?
class Person{
say(){
function hello(){
console.log('hello:',this) //undefined
}
hello(); //这个分号必须加,不然无法识别下面这个立即执行函数
//立即执行函数
(function fn(){
console.log('imeditately:',this) //undefined
})()
}
}
Person.prototype.talk = function(){
function fn1(){
console.log('fn1:',this) //this指向window
}
//立即执行函数
(function f2(){
console.log('f2:',this) //this指向window
})()
fn1()
}
let p =new Person()
p.say()
console.log('---------------------------------------------')
console.log('--------以下是talk函数执行结果---------------------------')
p.talk()
写回答
2回答
-
双越
2022-02-25
这种情况我也之前没遇到过,按我们阅读代码理解,这 4 应该都是 window 。
不过也没关系,日常使用中基本不会用这个 this 。class 里面都是用实例的 this 对象。
10 -
是奶茶呀
2022-04-20
函数中的this,谁调用指向谁,如果没加调用对象,那就是window,window调用是可以被省列不写的,所以是undefined
00
相似问题