每天 10 分钟,学习 JavaScript —— (七)函数中的 this

151 阅读1分钟

this 是什么 ?

  • 任何函数本质上都是通过某个对象调用的,如果没有直接指定就是 window
  • 所有函数内部都有一个变量 this
  • 它的值是调用函数的当前对象

如何确定 this 的值 ?

  • test():window
  • p.test():p
  • new test():新创建的对象
  • p.call(obj):obj
    function Fun(color) {
      console.log(this)
      this.color = color
      this.getColor = function() {
        console.log(this)
        return this.color
      }
      this.setColor = function(color) {
        console.log(this)
        this.color = color
      }
    }
    Fun('red') // this 是 window
    var fun = new Fun('yellow') // this 是 fun
    fun.getColor() // this 是 fun
    var obj = {}
    fun.setColor.call(obj, 'black') // this 是 obj
    var test = fun.setColor
    test() // this 是 window