清淨
  • Java

    • Java 基础
  • 框架

    • Flyway
    • MapStruct
    • Spring Cloud
  • 中间件

    • Elasticsearch
    • Redis
    • RabbitMQ
    • Kafka
  • 三剑客

    • HTML
    • CSS
    • JavaScript
  • 进阶

    • jQuery
    • ECMAScript6
    • TypeScript
  • Vue

    • Vue2
    • Vue3
    • VuePress
  • Linux
  • Jenkins
  • Maven
  • MySQL
  • 插件工具
  • 代码集成
  • 其它

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • 设计模式
迁移日志
订阅号
微信订阅号
微信订阅号
GitHub
  • Java

    • Java 基础
  • 框架

    • Flyway
    • MapStruct
    • Spring Cloud
  • 中间件

    • Elasticsearch
    • Redis
    • RabbitMQ
    • Kafka
  • 三剑客

    • HTML
    • CSS
    • JavaScript
  • 进阶

    • jQuery
    • ECMAScript6
    • TypeScript
  • Vue

    • Vue2
    • Vue3
    • VuePress
  • Linux
  • Jenkins
  • Maven
  • MySQL
  • 插件工具
  • 代码集成
  • 其它

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • 设计模式
迁移日志
订阅号
微信订阅号
微信订阅号
GitHub
  • JavaScript

    • 简介
    • 数据类型
    • 基本语法
    • 对象
    • 函数
    • 作用域
    • this
    • 垃圾回收
    • 数组
    • 字符串
    • 正则表达式
    • DOM API
    • BOM
    • 定时器
    • 执行上下文
    • 闭包

this

解析器在调用函数时,会向函数内部传递一个隐藏的参数 this,this 指向当前调用的对象。

  • 示例1

    function fun() {
      console.log(this);
    }
    fun(); // Window
    // 等价代码如下
    window.fun(); // fun函数被 Window 对象调用
    
  • 示例2

    function fun() {
      console.log(this);
    }
    var person = {
      name:'zs',
      method:fun
    }
    person.method(); // Object,此时不再是 Window
    
  • 示例3

    var name = 'window的name';
    function fun() {
      console.log(this.name);
      // console.log(name); // 永远都是 window.name
    }
    var person = {
      name:'zs',
      method:fun
    }
    fun(); // window 的 name
    person.method();  // zs
    
  • 示例4

    function Person(color) {
      console.log(this)
      this.color = color;
      this.setColor = function(color) {
        console.log(this)
        this.color = color
      }
      this,getColor = function() {
        console.log(this)
        return this.color
      }
    }
    
    Person('color'); // this是 window,且只有一条输出语句
    var per = new Person('color'); // this 是 per,且只有一条输出语句
    per.getColor();; // this 是 per
    var obj = {};
    per.setColor.call(obj,'green'); // this 是 obj
    var test = p.setColor;
    test(); // this 是 window
    
    function f1() {
      function f2() {
        console.log(this);
      }
      f2();
    }
    f1(); // this 是 window
    

注意

任何函数本质上都是通过对象调用的,而 this 就指向这个对象。如果函数调用时没有指定对象,那么默认就由 window 来调用,此时的 this 就是 window。

想要编辑此页?
上次更新: 2025/6/4 23:16
贡献者: Junfeng Dai
←作用域垃圾回收→
[ 纸上得来终觉浅绝知此事要躬行 ]
Copyright © 2021-present Junfeng Dai
蜀ICP备2021009537号