你是个什么this啊?

在JavaScript中有一个神奇的关键字,那就是大名鼎鼎的this,能够说,掌握了this才算进入了JavaScript的大

this关键字的含义很是明确,就是指代当前的对象,那么什么是“当前”就是咱们要重点关注的了。bash

在JavaScript中this的含义要更丰富,它能够是全局对象、当前对象或者任意对象,这彻底取决于函数的调用方式。JavaScript中函数的调用有如下几种方式:做为对象方法调用,做为函数调用,做为构造函数调用,和使用apply或call调用。app

做为函数调用

这是咱们最经常使用的方法,这种调用方式属于全局调用,这里的this就成了全局对象。函数

function f(){
    this.n = "hello";
    console.log(this.n);
    console.log(this);
}
f(); // hello    window

复制代码

调用f时,输出了"hello"还有window。this

var n = "hello"
    function f(){
        console.log(this.n);
    }
    f();// hello
复制代码

调用f时,仍然输出了hello。spa

做为对象方法调用

var name = "cat";
    var dogs = {
        name:"tom",
        showName:function(){
            console.log(this.name);
        }
    }
    dogs.showName();// 输出tom
    var otherName = dogs.showName;
    otherName();// 输出cat
复制代码

快来看,当执行dogs.showName();时,输出tom,说明这个时候this是指向dogs这个对象的。而当咱们尝试把dogs.showName赋给otherName时,咱们很容易想到这个showName()是作什么用的,显然输出它函数的执行环境所指向对象的name,而此时otherName变量至关于window对象的一个属性,所以otherName()执行的时候至关于window.otherNAme(),即window对象调用otherName这个方法,因此this关键字指向window,因此会输出cat。code

做为构造函数调用

JavaScript中的构造函数也很特殊,构造函数,其实就是经过这个函数生成一个新对象(object),这时候的this就会指向这个新对象,若是不用new调用,则和普通函数同样。对象

function f(){
        this.n = "hello";
    }
    var other = new f();
    console.log(other.n);//hello
复制代码

再来看,咱们为f函数new(构造)了一个新的对象other,那么this就会指向这个对象,因此会输出hello。ip

使用apply或call调用

apply()是函数对象的一个方法,它应用某一对象的一个方法,用另外一个对象替换当前对象。string

var n = "hello";
    function f(){
        console.log(this.n);
    }
    var a = {};
    a.n = "hey";
    a.m = f;
    a.m.apply();//hello
复制代码

在这段代码中,当apply()的参数为空时,就是没有对象区替换掉当前的对象,因此默认调用全局对象。所以,会输出hello,证实this指的是全局对象。那么试试给apply()指定一个对象。it

var n = "hello";
    function f(){
        console.log(this.n);
    }
    var a = {};
    a.n = "hey";
    a.m = f;
    a.m.apply(a);//hey
复制代码

此时输出了hey,说明对象替换成功,this指向了a这个对象。