this的值是在 函数执行时 决定的,不是在 函数定义时 决定
function test(){
console.log('this',this)
}
test()
test.call({name:'小甜甜'})
test.apply({name:'小甜甜'})
const boundTest test.bind({name:'小甜甜'})
boundTest()
class Person{
constructor(name,age){
console.log('constructor 里的 this',this);
this.name = name;
this.age = age;
}
test(){
console.log('对象方法里的 this',this)
}
asyncTest(){
console.log('this',this)
setTimeout(function(){
console.log('setTimeout 回调中的 this',this)
},0)
}
}
const zhangsan = new Person('张三',20);
zhangsan.test()
zhangsan.asyncTest()
bind函数
1.改变 this 指向
2.第一个参数是this的值,后面的参数是函数接收的函数的值
3.返回值不变
function test(a,b,c){
console.log(a,b,c);
console.log(‘this’,this);
return '我是哈默';
}
// 普通执行
const result = test(1,10,100)
//通过bind函数改变this指向
const boundTest = test.bind({name:'哈默'},7,77,777);
//改变后执行
const boundResult = boundTest()
console.log('result',result)
console.log('boundResult',boundTest)