咱们在js中常常看到this这个关键字,那么他是什么呢?它能够是全局对象、当前对象,也能够是任意对象,函数的调用方式决定了 this 的值。javascript
1. 方法中的this。java
在对象方法中, this 指向调用它所在方法的对象。例如:数组
var information = { name: "alan", age : "18", all : function() { return this.name + " " + this.age; } };
在这里,this 表示 information 对象。all 方法所属的对象就是 information。app
2. 单独直接调用this.函数
单独使用 this,则它指向全局(Global)对象。例如:this
var name = this; && "use strict";(严格模式) var name = this;
3. 函数中调用this.spa
在函数中,函数的所属者默认绑定到 this 上。例如:prototype
function information() { return this; } && "use strict";(严格模式) function information() { return this; }
4. 箭头函数调用this.code
ES6 新增了箭头函数,箭头函数不只更加整洁,还对 this 的指向进行了改进。箭头函数会从做用域链的上一层继承 this。orm
var obj = { y: function() { console.log(this === obj) var getX = () => { console.log(this === obj) } getX() } } obj.y() // true // true
和普通函数不同,箭头函数中的 this 指向了 obj,这是由于它从上一层的函数中继承了 this,你能够理解为箭头函数修正了 this 的指向。例如:
var x = 1 var obj = { x: 2, y: function() { var getX = () => { console.log(this.x) } return getX() } } obj.y() // 2 var a = obj.y a() // 1
obj.y() 在运行时,调用它的对象是 obj,因此 y 中的 this 指向 obj,y 中的箭头函数 getX 继承了 y 中的 this,因此结果是 2。若是咱们先将 y 赋值给全局做用域中的变量 a,a 在运行时,y 中的 this 便指向了全局对象,因此获得的结果是 1(非严格模式)。
5. js事件中调用this.
this 指向了接收事件的 HTML 元素。例如:
<button onclick="this.style.display='block'">显示</button>
6. 使用call和apply
改变 this 的指向,可使用 call 或 apply 方法,它们均可以改变函数的调用对象。将一个对象做为第一个参数传给 call 或 apply,this 便会绑定到这个对象。若是第一个参数不传或者传 null 、undefined,默认 this 指向全局对象(非严格模式)或 undefined(严格模式)。
var x = 1; var obj = { x: 2 } function getX() { console.log(this.x) } getX.call(obj) // 2 getX.apply(obj) // 2 getX.call() // 1 getX.apply(null) // 1 getX.call(undefined) // 1
使用 call 和 apply 时,若是给 this 传的不是对象,JavaScript 会使用相关构造函数将其转化为对象,好比传 number 类型,会进行 new Number()
操做,传 string 类型,会进行 new String()
操做。
function demo() { console.log(Object.prototype.toString.call(this)) } demo.call('hello') // [object String] demo.apply(5) // [object Number]
call 和 apply 的区别在于,call 的第二个及后续参数是一个参数列表,apply 的第二个参数是数组。参数列表和参数数组都将做为函数的参数进行执行。
var x = 1 var obj = { x: 2 } function getSum(y, z) { console.log(this.x + y + z) } getSum.call(obj, 3, 4) // 9 getSum.apply(obj, [3, 4]) // 9
7. bind方法调用this.
bind 方法会建立一个新函数,新函数的 this 会永久的指向 bind 传入的第一个参数。例如:
var x = 1 var obj_1 = { x: 2 } var obj_2 = { x: 3 } function getX() { console.log(this.x) } var a = getX.bind(obj_1) var b = a.bind(obj_2) getX() // 1 a() // 2 b() // 2 a.call(obj_2) // 2
虽然咱们尝试给函数 a 从新指定 this 的指向,可是它依旧指向第一次 bind 传入的对象,即便是使用 call 或 apply 方法也不能改变这一事实。
this 是 JavaScript 中很是重要的关键字,不一样的运行环境和调用方式都会对 this 产生影响。理解它能让咱们更熟练地使用这门语言!