js高级_97、函数中的this

this是什么?

*任何函数本质上都是通过某个对象来调用的,如果没有直接指定this那么this就是window对象。

*所有函数内部都有一个变量this,它的值是调用该函数的当前对象。

*一般异步任务的this是wondow,因为是定时器模块最后交给js引擎(window)调用的。箭头函数写法除外。箭头函数就代表直接指定了this了。

如何确定this的值

简单来说就是:谁调用的该函数那么this就是谁。如:

*test():this是window

new test():this是新创建的对象,因为new关键字会将this指向创建的实例。

p.test():this是p

p.call(obj):this就是obj

比如:

unction Person(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;
    };
  }
  Person("red"); //this是谁? window
  var p = new Person("yello"); //this是谁? p
  p.getColor(); //this是谁? p
  var obj = {};
  p.setColor.call(obj, "black"); //this是谁? obj
  var test = p.setColor;
  test(); //this是谁? window
  function fun1() {
    function fun2() {
      console.log(this);
    }
    fun2(); //this是谁? window
  }
  fun1();
posted @ 2022-03-13 08:55  青仙  阅读(39)  评论(0编辑  收藏  举报