machao07 / interview-questions

前端技术栈相关面试知识点( Vue、React、Typescript、JavaScript...),喜欢请点start

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

谈谈this对象的理解

machao07 opened this issue · comments

1、定义

this 关键字 是函数运行时自动生成的一个内部对象,只能在函数内部使用,总指向调用它的对象

this在函数执行过程中,this一旦被确定了,就不可以再更改

var a = 10;
var obj = {
  a: 20
}

function fn() {
  this = obj; // 修改this,运行后会报错
  console.log(this.a);
}

fn();

全局对象,this 指向 Window

2、绑定规则

默认绑定、隐式绑定、new绑定、显示绑定

默认绑定

全局环境中定义person函数,内部使用this关键字

var name = 'Jenny';
function person() {
    return this.name;
}
console.log(person());  //Jenny

调用函数的对象在浏览器中位window,因此this指向window

严格模式下,不能将全局对象用于默认绑定,this会绑定到undefined

隐式绑定

函数还可以作为某个对象的方法调用,这时this就指这个上级对象

例:

function test() {
  console.log(this.x); // this 指向 obj
}

var obj = {};
obj.x = 1;
obj.m = test;

obj.m(); // 1

this 指向 obj

这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象

例:

var o = {
    a:10,
    b:{
        fn:function(){
            console.log(this.a); //undefined
        }
    }
}
o.b.fn();

this 指向 b

new 绑定

通过构建函数new关键字生成一个实例对象,此时this指向这个实例对象

function test() {
 this.x = 1;
}

var obj = new test();
obj.x // 1

new过程遇到return一个对象,此时this指向为返回的对象

function fn()  
{  
    this.user = 'xxx';  
    return {};  
}
var a = new fn();  
console.log(a.user); //undefined

如果返回一个简单类型的时候,则this指向实例对象

function fn()  
{  
    this.user = 'xxx';  
    return 1;
}
var a = new fn;  
console.log(a.user); //xxx

注意的是null虽然也是对象,但是此时new仍然指向实例对象

function fn()  
{  
    this.user = 'xxx';  
    return null;
}
var a = new fn;  
console.log(a.user); //xxx

显示修改

apply()、call()、bind()是函数的一个方法,作用是改变函数的调用对象

var x = 0;
function test() {
 console.log(this.x);
}

var obj = {};
obj.x = 1;
obj.m = test;
obj.m.apply(obj) // 1

3、箭头函数

箭头函数的this能够在编译的时候就确定了this的指向

const obj = {
  sayThis: () => {
    console.log(this);
  }
};

obj.sayThis(); // window 因为 JavaScript 没有块作用域,所以在定义 sayThis 的时候,里面的 this 就绑到 window 上去了
const globalSay = obj.sayThis;
globalSay(); // window 浏览器中的 global 对象

绑定事件监听(箭头函数), 此时this指向了window

const button = document.getElementById('mngb');
button.addEventListener('click', ()=> {
    console.log(this === window) // true
    this.innerHTML = 'clicked button'
})

包括在原型上添加方法时候,此时this指向window

Cat.prototype.sayName = () => {
    console.log(this === window) //true
    return this.name
}
const cat = new Cat('mm');
cat.sayName()

4、优先级

new绑定优先级 > 显示绑定优先级 > 隐式绑定优先级 > 默认绑定优先级