关于this

89 阅读2分钟

this

this是什么?

this对象在运行时基于函数的执行环境绑定的: this 是在运行时进行绑定的,并不是在编写时绑定,它的上下文取决于函数调用时的各种条件。 this 的绑定和函数声明的位置没有任何关系,只取决于函数的调用方式。在全局函数中,this等于window,当函数被作为某个对象的方法调用时,this等于那个对象,不过匿名函数的执行环境具有全局性,因此this通常指向window,如果要判断一个运行中函数的 this 绑定,就需要找到这个函数的直接调用位置。找到之后就可以顺序应用下面这四条规则来判断 this 的绑定对象。

this的四大原则

  1. new 指向这个新对象。使用 new 实例化对象,在构造函数中的this指向实例化对象。
function Person(name) {
        this.name = name;
        console.log(name);
    }
      
    var person1 = new Person('Messi'); //Messi
  1. 箭头函数的this指向哪里?使用call或apply改变this的指向。 箭头函数的是没有属于自己的this的,它所谓的this是捕获其上下文的this,作为自己的this,所以箭头函数不会被new调用,所谓的this也不会被改变 我们可以用Babel理解一下箭头函数:
// ES6
    const obj = {
        getArrow() {
            return () => {
                console.log(this === obj);
            };
        }
    } 

    // ES5,由 Babel 转译
    var obj = {
        getArrow: function getArrow() {
            var _this = this;
            return function () {
                console.log(_this === obj);
            };
        }
    };

  1. 如果函数被调用的位置存在上下文,那么函数被隐式绑定,对象函数调用,哪个对象调用就指向哪个对象。
function f() {
        console.log( this.name );
    }
    
    var obj = {
        name: "Messi",
        f: f
    };
    
    obj.f(); //被调用的位置恰好被对象obj拥有,因此结果是Messi
  1. 默认情况下,指向全局,浏览器的话就是指向window,在严格模式下绑定到 undefined
   var a = 123
        function test(){
            console.log(this)
        }
        test()//winndow