What is this?

  • Any function is essentially called from an object, and if not specified directly it is a window
  • All functions have a variable this inside them
  • Its value is the current object on which the function is called

How do I determine the value of this?

  • The test () : the window
  • P.t est () : p
  • New test() : Newly created object
  • P.c all (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 is a window
    var fun = new Fun('yellow') / / this is fun
    fun.getColor() / / this is fun
    var obj = {}
    fun.setColor.call(obj, 'black') / / this is obj
    var test = fun.setColor
    test() / / this is a window
Copy the code