this
作为对象方法调用
this在对象方法中调用时,this指向当前对象
let a = 1
let obj = {
a: 2,
getA: function() {
console.log(this === obj); // true
console.log(this.a) // 2
}
}
普通函数中调用
在普通函数中this总是指向全局的
<script>
var a = "全局";
function getThis() {
let a = "函数上下文"
console.log(this)
console.log(this.a, 'getThis')
getThis1()
}
function getThis1() {
console.log(this)
console.log(this.a, 'getThis1')
obj.getA()
}
let obj = {
a: 'obj',
getA: function() {
console.log(this) // obj对象
console.log(this.a) // obj
}
}
getThis()
</script>
构造函数
构造函数使用new默认返回的对象就是构造函数内this指向的对象,但手动返回就不一定
<script>
// 构造函数默认返回值.
function Fun() {
this.name = '张三'
this.age = 12
this.say = function() {
alert('hello')
}
}
let newObj = new Fun()
console.log(newObj.name) // 张三
// 手动返回
function Handle() {
this.name = '李四'
this.age = 12
// 手动返回数据
return {
name: '王麻子'
}
}
let obj = new Handle()
console.log(obj.name, obj.age) // 王麻子 undefined
</script>
call、apply改变this指向
call、apply可以动态的改变函数this
<script>
let a = {
name: 'a',
funa: function() {
console.log(this.name)
}
}
let b = {
name: 'b'
}
a.funa() // a
a.funa.call(b) // b this指向了b
a.funa.apply(b) // b
</script>
call和apply
ECAMScript 3给Function的原型定义了两个方法,它们是Function.prototype.call和Function. prototype.apply
call和apply的区别
call和apply作用一样一样的,只是传参形式不一样
apply: 两个参数,第一个参数是要绑定的this对象,第二个是个数组或者类数组
function fun(a, b, c) {
console.log(a, b, c) // 1, 2, 3
}
let d = {}
fun.apply(d, [1, 2, 3])
call参数无数个,第一个参数与apply一样是要绑定的this对象,后面的参数是依次传入参数
unction fun(a, b, c) {
console.log(a, b, c) // 1, 2, 3
}
let d = {}
fun.call(d, 1, 2, 3)
call和apply第一个参数为null,this指向原宿主对象。在严格模式下this会指向null
call和apply可以用来做什么
1.改变this的指向
2.Function.prototype.bind
我们常用的bind方法实际是apply和call封装来得,改变this指向正真起作用的是apply,所以在绑定bind的时候不会立即执行,要调用的时候才会执行,而,call和apply都是立即执行的
3. 借用其他对象的方法