普通函数内:
function study() {
console.log(this);
}
let study1 = function() {
console.log(this);
}
study(); // window 对象
study1(); // window 对象
let user = {
name: 'zs',
age: 12,
walk: function() {
console.log(this);
}
}
user.walk(); // this指向方法在的那个对象
user.study = study; // study函数赋值给对象的函数
user.study(); // 对象调用study
得出结论:
- 普通函数内的this指向决定于谁调用的函数,this就指向谁
- 没有明确谁调用的时候this指向window顶级对象
箭头函数内:
console.log(this); // window对象
let study = function() {
console.log(this);
}
let user = {
name: 'zs',
age: 22,
sleep: () => {
console.log(this);
},
eat: function() {
console.log(this);
// 对象内的函数内的箭头函数 this指向当前对象
let eat_in = () => {
console.log(this);
}
eat_in();
},
}
user.study = study;
user.study(); // 对象调用普通函数 this指向对象
user.sleep(); // 对象调用自身的箭头函数 this指向window对象
user.eat(); // 对象调用对象内的普通函数 this指向对象
得出结论:
- 箭头函数中访问的
this
,是箭头函数所在作用域的this
变量。- 所以不推荐在箭头函数内使用this
修改this的指向:
Js中有三种方法可以动态指定普通函数中
this
的指向
call方法:
function count(x, y) {
console.log(this);
return x + y;
}
let user = {
name: 'zs',
age: 22,
}
let stu = {
name: 'ls',
age: 22,
}
// this指向user对象 参数为 5 5
let jie = count.call(user, 5, 5);
console.log(jie);
// this指向stu对象 参数为 3 3
let jie2 = count.call(stu, 3, 3)
console.log(jie2);
-
call
方法能够在调用函数的同时指定this
的值 -
使用
call
方法调用函数时,第1个参数为this
指定的值 -
call
方法的其余参数会依次自动传入函数做为函数的参数
apply方法:
- apply和call方法基本一致
apply方法有两个参数
参数1为修改this指向的值
参数2为一个数组 数组里面为
函数.apply(this指向,[函数内参数1,函数内参数2]);
bind方法
bind方法修改this指向会返回一个新的函数
function count(x, y) {
console.log(this);
return x + y;
}
let user = {
name: 'zs',
age: 22,
}
let stu = {
name: 'ls',
age: 22,
}
let Count = count.bind(user);
let jie = Count(2, 3);
console.log(jie);