this的值

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值