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 @   青仙  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示