this 函数上下文,指向函数的调用方式
下面以例子来学习 this的指向
1.普通函数被独立调用
this指向window
2.定义在对象中,被独立调用
打印:undefined,被独立调用,相当于例子1,this指向window
3.定义在对象中,被对象调用
var obj = {
name: "why",
bar: function() {
console.log("bar:", this.name)
}
}
obj.bar()
打印:why,this指向bar()函数被调用的对象obj
4.定义在对象中,被对象调用
worker.hand.work() 被hand调用 指向hand
workerwife.work() 被workerwife调用 指向workerwife
5.new一个实例
this指向aa,打印 person { name: 'AAA' }
6.new一个实例,赋给其他对象
teacher.buy() 指向teacher 打印BBB
workerwife.buy()指向workerwife 打印workerwife
7.apply
this指向apply的第一个参数 打印 this { name: 'worker' } aa bb cc
apply调用后会立即执行
8.call
this指向call调用的第一个参数 打印 this { name: 'worker' } aaa bbb ccc
call调用后会立即执行
9.bind
this指向call调用的第一个参数 打印 this { name: 'worker' } aaa bbb ccc
bind调用后不会立即执行,也可以在bind的时候不传参,执行的时候传
10.箭头函数
箭头函数的this指向:箭头函数定义时离箭头函数最近的非箭头函数的执行上下文的this。
结果
buy1和buy3是箭头函数,定义时最近的非箭头函数 person1()的上下文,person1被call执行,this指向tercher
buy1和前面console.log('this buy',this) 里面的this是同一个对象,谁调用他们就指向谁
buy2是普通函数,是独立调用的,this指向window
11.箭头函数2
function outer(){ console.log('outer this ',this);//1. outer函数被worker对象调用 指向worker const work = ()=>{ console.log('work this ',this);//3. work箭头函数被定义在outer里面 outer的上下文是worker inner2() } const work2 = ()=>{ console.log('work2 this ',this);//5. work2箭头函数被被定义在outer里面 outer的上下文是worker } function inner2(){ console.log('inner2 this ',this);//4. inner2函数被独立调用 指向windows work2() } function inner(){ console.log('inner this ',this);//2. inner函数被独立调用 指向windows work() } inner() } var worker = { name : 'worker' } worker.outer = outer worker.outer()
13.操纵箭头函数的this
指向
需要在箭头函数定义之前就给this
修改方向
const obj = {
fun2: function () {
console.log('B0',this);
return function () {
console.log('B1',this);
return () => {
console.log('B2',this);
}
}
}
}
let f2 = obj.fun2();//obj
let f2_2 = f2(); // window
f2_2() // window
上面的例子中箭头函数的this指向 windows
修改外层代码库的this
指向:(bind,call,apply都可以改变外层指向)
const obj = {
fun2: function () {
console.log('B0',this);
return function () {
console.log('B1',this);
return () => {
console.log('B2',this);
}
}
}
}
let f2 = obj.fun2();//obj
// let f2_2 = f2(); // window
// f2_2() // window
let f2_2 = f2.bind(obj)()//obj
f2_2()//obj