一、this指向
1. 普通函数
function fn1() {
console.log(this) // window
}
而严格模式下, this为undefined
function fn2() {
"use strict";
return this;
}
fn2() === undefined; // true
2. 构造函数
function Person(name, sex) {
this.name = name
this.sex = sex
console.log(this) // this指向 Person 的实例对象 p
}
let p = new Person(18, '阴阳')
3. 对象方法
a.函数的定义位置不影响其this指向,this指向只和调用函数的对象有关
b.多层嵌套的对象,内部方法的this指向被调用函数最近的对象
let obj = {
name: 'li',
getName() {
console.log(this.name) // this指向obj
},
innerObj: {
name: 'son',
getSonName() {
console.log(this.name) // this指向innerObj
}
}
}
obj.getName()
4. 事件绑定
let oBtn = document.getElementById("btn-box")
oBtn.onclick = function() {
console.log(this); // btn
}
5. 箭头函数
由于箭头函数不绑定this, 它会捕获其所在(定义的位置)上下文的this值, 作为自己的this值;下图可以看到,箭头函数在setTimeout中的this指向了构造函数新生成的对象,而普通函数指向了全局window对象
二、修改this指向
1. call
call(thisScope, arg1, arg2, arg3...)
2. apply
apply(thisScope, [arg1, arg2, arg3...]);两个参数
apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表
3. bind
bind改变this指向后,返回的是函数
let info1 = {
name: "小sun",
gender: 0,
age: 24,
say: function(looks, grade) {
console.log(this.name, this.gender, this.age)
}
}
let info2 = {
name: "小李",
gender: 1,
age: 18
}
info1.say.call(info2 ,"小帅哥","大班")
info1.say.apply(info2 ,["小帅哥","大班"])
info1.say.bind(info2)("小帅哥","大班")
// this原先指向info1,现在指向info2
相似处
1、第一个参数都是this要指向的对象。
2、都可以利用传参。