什么是this?
在JS中,this其实是多余的,它的作用是让JS看起来像JAVA,this我理解为当前的执行环境。
全局中的this
全局中的this一般指向全局对象,浏览器中的全局对象就是 window。如:
console.log(this.document === document); //trueconsole.log(this === window); //truethis.a = 1234;console.log(window.a); //1234
普通函数的 this
一般函数的 this也是指向 window,在 nodeJS 中为 global object。如:
function fn () {return this;}console.log(fn() === window);//true, global object
需要注意的是在严格模式中,函数的 this 为 undefined,因为严格模式禁止this关键字指向全局对象:
function a1 () {"use strict";//使用严格模式return this;}console.log(a1() === undefined);//true
对象方法的函数的 this
var o = {age: 18,f: function() {return this.age;}};console.log(o.f()); // 18
f 为对象 o 的方法。这个方法的 this 指向这个对象,在这里即对象 o。
普通函数调用
函数也可以直接被调用,此时 this 绑定到全局对象。在浏览器中,window 就是该全局对象。
window.name = 'globalName';var getName = function(){return this.name};console.log(getName());//globalName
对象原型链上的this
var o = {f: function() {return this.a + this.b;}};var p = Object.create(o);p.a = 1;p.b = 2;console.log(p.f()); //3
通过 var p = Object.create(o) 创建的对象,p 是基于原型 o 创建出的对象。
p 的原型是 o,调用 f() 的时候是调用了 o 上的方法 f(),这里面的 this 是可以指向当前对象的,即对象 p。
构造器中的 this
function MyClass() {this.a = 25;}var o = new MyClass();console.log(o.a); //25
new MyClass() 的时候,MyClass()中的 this 会指向一个空对象,这个对象的原型会指向 MyClass.prototype。MyClass()没有返回值或者返回为基本类型时,默认将 this 返回。
function a2() {this.a = 18;return {a: 28};}o = new a2();console.log(o.a); //28
call/apply 方法与 this
在call/apply 方法中,this永远指向它的第一个参数。如:
function add(c, d) {return this.a + this.b + c + d;}var o = {a: 1,b: 3};add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
在遇到this产生困惑的时候,建议先将其改写成call/apply的形式,更方便判断。
