js中的this指向问题
this指向两句话口诀:
1.this永远指向函数执行的环境,而不是声明的环境
2.箭头函数的this指向父级
一、正常函数的this
function fn1(){ console.log(this) } fn1() //this===window fn1.call({x:100}) //this==={x:100} const fn2 = fn1.bind({x:200}) fn2() //this==={x:200}
二、对象的this和箭头函数的this
const zhangsna = { name:'张三', sayHi(){ console.log(this) //this是当前对象 } wait(){ settimeOut(function(){ console.log(this) //this是window }) } } const zhangsna = { name:'张三', sayHi(){ console.log(this) //this是当前对象 } wait(){ settimeOut(()={ console.log(this) //this是当前对象 }) } }
三、构造函数的this
1 class People { 2 constructor(name){ 3 this.name = name 4 this.age = age 5 } 6 sayHi(){ 7 console.log(this) 8 } 9 } 10 11 let person = new People('张三') 12 person.sayHi() //person对象

浙公网安备 33010602011771号