啥是 this ?

68 阅读1分钟

先说结论,this 就是 call 的第一个参数

第一个例子:
要调用函数f1,通常都写成f1(),它其实是 call 的语法糖,调用函数原本的写法是 f1.call( undefined ),即:

f1() 等价于 f1.call( undefined ) // 无参数
f1('hi') 等价于 f1.call( undefined, 'hi' ) // 有参数

此时 this 就是 undefined
然而当浏览器发现 this === undefined时,会将 this转成window
Node.js 根据版本不同会将 this转成globle或者干脆不变

第二个例子:
object.child.f1()的原本写法是f1.call( object.child )

object.child.f1() 等价于 f1.call( object.child ) // 无参数
object.child.f1('hi') 等价于 f1.call( object.child, 'hi' ) // 有参数

此时 this 就是 object.child

知道上面两种【转换代码】后,来看下面的代码

var length = 4
function callback(){
  console.log(this.length) // 打印出什么?
}

const obj = {
  length: 5,
  method(callback){
    callback() // 仅此一处调用,callback()等价于callback.call(undefined),经过浏览器转换得 this === window,那么 this.length 就是 4
  }
}
obj.method(callback, 1, 2) //输出4