this是什么?
this
是 JavaScript 语言的一个关键字
this
指的是函数运行时所在的环境(context)
1.普通的this
- 全局调用,this指向window
var x = 1;
function test() {
console.log(this) // window
console.log(this.x); // 1
}
test();
- 作为某个对象的方法调用,这时this就指这个上级对象。
function test() {
console.log(this);
}
var obj = {
name: 'zs',
fn: test
};
obj.fn(); // {name: "zs", fn: ƒ}
2.new 的this,构造函数调用
构造函数,通过这个函数,生成一个新对象。这时,this
指向这个新对象
function Student() {
this.name = 'zhangsan'
}
let stu1 = new Student();
console.log(stu1); // Student { name: "zhagnsan" }
3.call、apply和bind
javascript,在Function的porpertype上提供了3个方法来强行修改this,分别是 call、apply、bind
- call和apply使用方法相同,参数不同
- call ( context, param1 , param2 , param3 )
- apply( context, [param1 , param2 , param3] )
- call和apply都会立即执行函数
- bind方法传参和call一致,不会立即执行,而是返回一个绑定新this的函数
function fn() {
console.log(this);
}
fn.call({name: 'zs'}, 1, 2, 3); // {name: 'zs'}
fn.apply({name: 'ls'}, [1, 2, 3]); // {name: 'ls'}
let newFn = fn.bind({ age: 18 }, 1, 2, 3);
newFn(); // {age: 18}
4.ES6箭头函数里的this
箭头函数的this是在定义时所在的对象。
ES6 标准入门-阮一峰
this指向的固定化并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以不能用作构造函数。
箭头函数没有自己的this,当然也不能通过call(),apply(),bind()改变this的指向
可以通过修改父级的 this 指针,来达到子箭头函数 this 的修改