this指向调用函数的对象
this一定指向一个对象(面向对象:函数一定是被某个对象调用)
1.全局作用域下,this始终指向window对象。
console.log(this);//window
2.函数内部的this,在非严格模式下,指向window对象:
aa()
function aa(){
bb()
console.log(this)//window
function bb(){
console.log(this)//window
}
}
3.函数内部的this,在严格模式下:
aa();
window.aa();
function aa() {
'use strict'
console.log(this);
}
//使用aa()调用时,this是undefined,使用window.aa()调用时,指向window
4.对象中的this,谁调用就指向谁
const obj = {
fn: function () {
console.log(this)
},
abc: {
fn: function () {
console.log(this)
}
}
}
obj.fn();//obj
obj.abc.fn();//obj.abc
/*
如果对象b继承对象a:
*/
const a = {
fn:function(){
console.log(this)
}
}
const b = Object.create(a);
b.fn();//this指向b
a.fn();//this指向a
5.箭头函数中的this
箭头函数中没有this和arguments。
它会捕获自己定义所处的外层执行环境,并且继承这个this值,指向当前定义时所在的对象。箭头函数的this指向在被定义的时候就确定了, 之后永远都不会被改变,即使使用call apply() bind()等方法改变this指向也不可以
const obj = {
abc: {
fn: () => {
console.log(this)
}
}
}
obj.abc.fn();
因为obj在window作用域下,所以箭头函数的this指向window。
6.构造函数中的this:
构造函数在生成对象时,this指向生成的对象实例。没有生成前,函数的this没有确定指向
function fn() {
this.a = 123;
this.b = function () {
console.log(this);
}
}
let abc = new fn();
abc.b();
7.原型链中的this:
指向它调用它的对象,而不是从原型链上找他它时,它所属于的对象。
const father = {
a: function () {
console.log(this)
}
}
const son = { b: 2 };
Object.setPrototypeOf(son, father)
father.a()//father
son.a()//son