JS中this的指向,this是js中的一个关键字
1.this的指向有这四种情况
1. 在普通的函数中,this指向全局对象window
2.在构造函数中,this指向创造出来的实例
3.对象的方法里面调用,this指向调用者
4. 在函数中,严格模式下,this 是 undefined
// 普通方法中
function bar () {
console.log(this) // this指向的是window
}
bar()
// 构造函数中
function Animal() {
this.name = 'zzz',
this.sayName = function () {
console.log(this) // 指向的是a实例
}
}
var a = new Animal()
a.sayName()
// 对象方法
var obj = {
name: '张三',
fullName: function () {
console.log(this.name)
}
}
obj.fullName() // 这的this指向 obj这个对象
// 函数严格模式下
<script type="text/javascript">
'use strict'
function a () {
console.log(this)
}
a() // undefined
</script>
2.改变this的指向
- apply() apply(thisScope, [arg1, arg2, arg3…]) 只接收两个参数,
- call() call(thisScope, arg1, arg2, arg3…) 接收多个参数
- bind() bind(thisScope, arg1, arg2, arg3…) 接收多个参数,返回一个函数。在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
第一个参数‘this’使用对象,后续参数作为参数传递给函数使用
// call 和 apply
function add (b, c) {
return this.a + b + c
}
var o = {a: 1};
console.log(add.apply(o, [4, 5])) // 1+4+5 = 10
console.log(add.call(o, 4, 7)) // 1+4+7 = 12
// g使用bind绑定后,再重新对新函数g绑定,bind只会生效第一次绑定的
function add (b, c) {
return this.a + b + c
}
var g = add.bind({a: 1}, 1, 2) // 4
console.log(g())
var c = g.bind({a: 10}, 1, 11) // 4
console.log(c())