this的取值机制
JavaScript 标准定义了 [[thisMode]] 私有属性
[[thisMode]] 私有属性有三个取值。
lexical:表示从上下文中找 this,这对应了箭头函数。
global:表示当 this 为 undefined 时,取全局对象,对应了普通函数。
strict:当严格模式时使用,this 严格按照调用时传入的值,可能为 null 或者 undefined。
"use strict"
function showThis(){
console.log(this);
}
var o = {
showThis: showThis
}
showThis(); // undefined
o.showThis(); // o
class 设计成了默认按 strict 模式执行
所以下面这种情况也返回undefined
class C {
showThis() {
console.log(this);
}
}
let o = new C()
let showThis = o.showThis
showThis() // undefined
改变this指向有三种方法
call、bind 和 apply :call和apply只是传值形式不同。bind则是返回一个绑定过this的函数,传值形式同call,一个个传。
当它们3个用于不接受 this 的函数类型如箭头、class 都不会报错。
虽然改变不了this,但是可以传参