作用域和自由变量

  • 全局作用域
  • 块级作用域
  • 函数作用域

自由变量

  • 一个变量在当前作用域没有定义,但是被使用
  • 向上一级作用域一层层依次寻找,直至找到为止
  • 直到全局作用域都没找到,则报错xx is not defined

this(在函数执行时定义)

作为普通函数

function fn1(){
console.log(this)
}
fn1() //window

使用call apply bind

fn1.call({x: 100})  //{x: 100}
const fn2 = fn1.bind({x:200})
fn2() //{x: 200}

作为对象方法被调用

  • 返回对象本身

在class方法中被调用

  • 返回实例本身

箭头函数

const zhangsan = {
name: '张三'
sayHi(){
// this指向当前对象
console.log(this)
},
wait(){
setTimeout(function(){
//this === window
console.log(this)
})
},
waitAgain(){ //箭头函数取上级作用域的值
setTimeout(()=>{
//this === 当前对象
console.log(this)
})
}
}

手写bind

bind作用

function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}

const fn2 = fn1.bind({ x: 100 }, 10, 20, 30)
console.log(fn2())

//result
this { x: 100 }
10 20
this is fn1

手写

Function.prototype.bindHand = function(){
// 拆解为数组
const args = Array.prototype.slice.call(arguments)
// 获取this
const t = args.shift()
// 原来的函数
const self = this
// 返回函数
return function(){
return self.apply(t, args)
}
}