在JavaScript中有一个神奇的关键字,那就是大名鼎鼎的this,可以说,掌握了this才算进入了JavaScript的大
this关键字的含义非常明确,就是指代当前的对象,那么什么是“当前”就是我们要重点关注的了。
在JavaScript中this的含义要更丰富,它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式。JavaScript中函数的调用有以下几种方式:作为对象方法调用,作为函数调用,作为构造函数调用,和使用apply或call调用。
作为函数调用
这是我们最常用的方法,这种调用方式属于全局调用,这里的this就成了全局对象。
function f(){
this.n = "hello";
console.log(this.n);
console.log(this);
}
f(); // hello window
调用f时,输出了"hello"还有window。
var n = "hello"
function f(){
console.log(this.n);
}
f();// hello
调用f时,仍然输出了hello。
作为对象方法调用
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。
作为构造函数调用
JavaScript中的构造函数也很特殊,构造函数,其实就是通过这个函数生成一个新对象(object),这时候的this就会指向这个新对象,如果不用new调用,则和普通函数一样。
function f(){
this.n = "hello";
}
var other = new f();
console.log(other.n);//hello
再来看,我们为f函数new(构造)了一个新的对象other,那么this就会指向这个对象,所以会输出hello。
使用apply或call调用
apply()是函数对象的一个方法,它应用某一对象的一个方法,用另一个对象替换当前对象。
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()指定一个对象。
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这个对象。