默认值
1.1普通函数
谁调用指向谁,严格模式下没有调用者时
this
的值为undefined
。
function fn() {
console.log(this);
}
fn();//输出window
1.2箭头函数
箭头函数中的
this
与普通函数完全不同,也不受调用方式的影响,事实上箭头函数中并不存在this
!箭头函数中访问的this
不过是箭头函数所在作用域的this
变量。
let sayHi = function () {
console.log(this); // 该箭头函数中的 this 为函数声明环境中 this 一致
};
let user = {
name: "小明",
// 该箭头函数中的 this 为函数声明环境中 this 一致
walk: () => {
console.log(this);
},
sleep: function () {
let str = "hello";
console.log(this);
let fn = () => {
console.log(str);
console.log(this); // 该箭头函数中的 this 与 sleep 中的 this 一致
};
// 调用箭头函数
fn();
},
};
// 动态添加方法
user.sayHi = sayHi;
// 函数调用
user.sayHi();
user.sleep();
user.walk();
定义值
2.1 callcall(this,形参1,形参2...形参n)
function sayHi() {
console.log(this);
}
let user = {
name: '小明',
age: 18
}
let student = {
name: '小红',
age: 16,
}
// 调用函数并指定 this 的值
sayHi.call(user); // this 值为 user
sayHi.call(student); // this 值为 student
2.2 applyapply(this,[形参1,形参2...形参n])
function counter(x, y) {
return x + y;
}
// 调用 counter 函数,并传入参数
let result = counter.apply(null, [5, 10]);
console.log(result);
2.3 bindcall(this,形参1,形参2...形参n)
bind
方法并不会调用函数,而是创建一个指定了 this
值的新函数,使用方法如下代码所示:
// 普通函数
function sayHi() {
console.log(this);
}
let user = {
name: '小明',
age: 18
}
// 调用 bind 指定 this 的值
let sayHello = sayHi.bind(user);
// 调用使用 bind 创建的新函数
sayHello();