Javasript中各种状态下的this指向

据我所知的有5种:
1.作为普通函数调用:this指向全局
2.作为对象的方法调用:this指向当前对象
3.作为构造器使用: this指向实例对象
4.用call、apply调用时:this指向所指定的上下文
5.在箭头函数中使用this时:this指向箭头函数开始定义的上下文
##作为普通函数调用

function test () {
	return this;
}
function test2 () {
	console.log(test());
}
let obj = {
	test: function() {
		console.log(test());
	}
}
console.log(test()); // window
test2(); // window
obj.test(); //window

##作为对象的方法调用

let obj = {
	test: function() {
		return this;
	}
}
console.log(Object.is(obj, obj.test())); // true

##作为构造函数调用

function Fn (num) {
	this.age = num;
}
let fn = new Fn(10);
let fn2 = new Fn(11);
console.log(fn.age); // 10
console.log(fn2.age); // 11

##使用call、apply调用

window.str = 'window';
let obj = {
	str: 'obj',
}
function test () {
	test.str = 'test';
	console.log(this.str);
}
test(); // 普通调用,this执行window, 输出window
test.call(obj); // obj
test.call(test); // test

##箭头函数的this

var fn = () => this; // 在全局下定义
function test () {  // 在全局下定义
	return this;
}
let obj = {
	fn: fn,  // 在obj对象中使用
	test: test,  // 在obj对象中使用
}
console.log(Object.is(obj.fn(), window)); // true
console.log(Object.is(obj.test(), obj)); // true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值