this 关键字

简略说,this就是属性或办法“以后”所在的对象。

this.property
var person = {  name: '张三',  describe: function () {    return '姓名:'+ this.name;  }};person.describe()// "姓名:张三"

下面代码中,this.name示意name属性所在的那个对象。因为this.name是在describe办法中调用,而describe办法所在的以后对象是person,因而this指向personthis.name就是person.name

应用场合

(1)全局环境

全局环境应用this,它指的就是顶层对象window

this === window // truefunction f() {  console.log(this === window);}f() // true

(2)构造函数

构造函数中的this,指的是实例对象。

var Obj = function (p) {  this.p = p;};

如果对象的办法外面蕴含thisthis的指向就是办法运行时所在的对象。该办法赋值给另一个对象,就会扭转this的指向。

var obj ={  foo: function () {    console.log(this);  }};obj.foo() // obj

下面代码中,obj.foo办法执行时,它外部的this指向obj

然而,上面这几种用法,都会扭转this的指向。

绑定 this 的办法

Function.prototype.call()

函数实例的call办法,能够指定函数外部this的指向(即函数执行时所在的作用域),而后在所指定的作用域中,调用该函数。

var obj = {};var f = function () {  return this;};f() === window // truef.call(obj) === obj // true

下面代码中,全局环境运行函数f时,this指向全局环境(浏览器为window对象);call办法能够扭转this的指向,指定this指向对象obj,而后在对象obj的作用域中运行函数f

Function.prototype.apply()

func.apply(thisValue, [arg1, arg2, ...])

apply办法的第一个参数也是this所要指向的那个对象,如果设为nullundefined,则等同于指定全局对象。第二个参数则是一个数组,该数组的所有成员顺次作为参数,传入原函数。原函数的参数,在call办法中必须一个个增加,然而在apply办法中,必须以数组模式增加。

function f(x, y){  console.log(x + y);}f.call(null, 1, 1) // 2f.apply(null, [1, 1]) // 2

Function.prototype.bind()

bind()办法用于将函数体内的this绑定到某个对象,而后返回一个新函数。

var d = new Date();d.getTime() // 1481869925657var print = d.getTime;print() // Uncaught TypeError: this is not a Date object.

下面代码中,咱们将d.getTime()办法赋给变量print,而后调用print()就报错了。这是因为getTime()办法外部的this,绑定Date对象的实例,赋给变量print当前,外部的this曾经不指向Date对象的实例了。

bind()办法能够解决这个问题。