前端知识点---this的使用方法详解(Javascript)

06-01 1632阅读

文章目录

  • this动态绑定 , this的用法
    • 01. 全局作用域下的 this
      • ①在浏览器中,this 指向 Window 对象。
      • ② 在Node.js环境中,this 指向 global 对象
      • ③特别说明
      • 02. 函数中的 this
        • 2.1 普通函数和匿名函数调用
        • 2.2 构造函数和调用
        • 2.3 箭头函数中的 this
        • 03对象方法调用
          • ①函数作为对象的方法调用
          • ② this 在对象的方法中使用
          • ③赋值
          • 04. 事件处理中的 this(事件处理函数)
          • 05. 动态绑定的方式
            • 5.1 call 方法
            • 5.2 apply 方法
              • ①基本语法
              • ②基础应用:求数组最值
              • 5.3 bind 方法
                • ①引子
                • ②基本用法
                • 06类中的 this
                • 07. 总结

                  前端知识点---this的使用方法详解(Javascript)

                  this动态绑定 , this的用法

                  在JavaScript中,this 是一个非常重要但是呢 也让人难搞明白的关键字。

                  **它的值不是在编写代码时静态确定的,而是在代码运行时动态绑定的。**这非常重要

                  this 不是指向函数本身,而是指向 调用函数的对象。根据调用方式的不同,this 会指向不同的对象

                  下面讲一下它 .

                  01. 全局作用域下的 this

                  在全局作用域中(即不在任何函数中),this 通常指向全局对象:

                  ①在浏览器中,this 指向 Window 对象。

                  console.log(this); // 浏览器中输出 Window
                  

                  ② 在Node.js环境中,this 指向 global 对象

                  console.log(this); // 在 Node.js 中输出:{} (指向 global 对象)
                  function showThis() {
                      console.log(this); // 在 Node.js 中输出:{} (指向 global 对象)
                  }
                  showThis();
                  

                  ③特别说明

                  在严格模式(‘use strict’)下,this 在全局作用域中将是 undefined,而不是 window 或 global。

                  'use strict';
                  console.log(this); // 在严格模式下输出:undefined
                  

                  02. 函数中的 this

                  this 在函数中的行为取决于调用的方式。

                  2.1 普通函数和匿名函数调用

                  当函数以普通方式调用时,this 默认指向全局对象(在严格模式下是 undefined)。

                  function foo() {
                    console.log(this);
                  }
                  foo(); // 浏览器中,this 指向 window
                  
                   //   匿名函数
                        setTimeout(function () {
                          console.log(this); //window
                        }, 1000);
                        console.log(this); //window
                  

                  在严格模式下:

                  "use strict";
                  function foo() {
                    console.log(this);
                  }
                  foo(); // undefined
                  

                  2.2 构造函数和调用

                  当一个函数用作构造函数(通过 new 关键字调用 创建一个新的对象实例,并将该对象与构造函数绑定)时,this 指向新创建的实例对象(关键) , 用于将属性和方法绑定到该对象。

                  function Person(name) {
                  //创建一个构造函数 , 参数为name
                    this.name = name;//this指向当前创建的实例对象 , 新对象有个名为name的属性 this.name = name; 将参数 name 的值赋给对象的 name 属性。
                  }
                  const person = new Person('Bob');
                  console.log(person.name); // 输出 'Bob'
                  
                  function Person(name, age) {
                    this.name = name; // this 绑定到新创建的对象
                    this.age = age;
                  }
                  const person1 = new Person('Alice', 25);
                  console.log(person1); // Person { name: 'Alice', age: 25 }
                  
                  function Car(brand, model) {
                    this.brand = brand; // 将 brand 绑定到新对象
                    this.model = model; // 将 model 绑定到新对象
                    this.getDetails = function() {
                      return `${this.brand} ${this.model}`;
                    };
                  }
                  const car1 = new Car('Toyota', 'Corolla');
                  console.log(car1.getDetails()); // Toyota Corolla
                  

                  补充:

                  function fn(){}和function Fn(){} javascript不会自动辨别他俩一个是普通函数一个是构造函数

                  是靠调用方式辨别的

                  function Person(name) {
                    console.log("Person 函数被调用");
                  }
                  Person("Alice"); // 普通函数调用
                  new Person("Bob"); // 构造函数调用
                  

                  为什么 Person 会被当作构造函数?

                  当你使用 new 关键字调用 Person,JavaScript 自动执行以下步骤:

                  • 创建一个新的空对象 {}。
                  • 将这个新对象的 proto 设为 Person.prototype(继承 Person 的原型)。
                  • 将 this 绑定到新对象(即 this 指向新创建的对象)。
                  • 执行 Person 函数,如果没有 return 语句或 return 不是对象,则返回这个新对象。

                    JavaScript 根据 new 关键字决定函数的执行方式,而不是在定义时判断:

                    function Person(name){
                    this,name = name;
                    }
                    const person = new Person('bob')//虽然函数的定义写在new Person之前, Person依旧是构造函数
                    

                    2.3 箭头函数中的 this

                    箭头函数不会创建自己的 this,它会继承来自其定义位置的外层上下文的 this。

                    const obj = {
                      name: 'Alice',
                      arrowFunc: () => {
                        console.log(this.name);
                      }
                    };
                    obj.arrowFunc(); // undefined, 因为箭头函数中的 this 绑定的是全局对象
                    而普通函数会绑定到调用它的对象:
                    const obj = {
                      name: 'Alice',
                      normalFunc: function() {
                        console.log(this.name);
                      }
                    };
                    obj.normalFunc(); // 输出 'Alice'
                    使用箭头函数时,this 会继承自外层作用域:
                    

                    03对象方法调用

                    ①函数作为对象的方法调用

                    函数作为对象的方法调用时,this 指向调用该方法的对象。

                    const obj = {
                      name: 'Alice',
                      sayName: function() {
                        console.log(this.name);//this 指向调用该方法的对象,即 obj
                      }// 应该是一个方法 是函数类型的方法
                    };
                    obj.sayName(); // 输出 'Alice'
                    

                    ② this 在对象的方法中使用

                    this 在对象的方法中使用时,this 指向调用该方法的对象。

                    const obj = {
                      name: 'Alice',
                      getName() {
                        return this.name;
                      }
                    };
                    console.log(obj.getName()); // 输出 "Alice"
                    

                    ③赋值

                    const obj1 = {
                      name: "Bob",
                      greet: function() {
                        console.log(this.name);
                      }
                    };
                    const obj2 = {
                      name: "Charlie"
                    };
                    obj2.greet = obj1.greet;// 将 obj1 的 greet 方法赋给 obj2
                    obj2.greet(); // "Charlie"
                    

                    尽管 greet 方法最初是定义在 obj1 上,但当我们将 greet 赋值给 obj2 后,调用 obj2.greet() 时,this 就指向了 obj2,而不是 obj1

                    04. 事件处理中的 this(事件处理函数)

                    在事件处理函数中,this 通常指向触发事件的 DOM 元素。

                    别点我
                    
                    const button = document.querySelector('button');
                    button.addEventListener('click', function() {
                      console.log(this); // 输出被点击的按钮元素
                    });
                    

                    前端知识点---this的使用方法详解(Javascript)

                    05. 动态绑定的方式

                    为什么要改变this的呢? 因为知道this的值一般不是我们想要的 , 比如箭头函数, 它没有自己的this . 所以下面讲一下 , 如何改变this的值 .

                    JavaScript 提供了三种显式绑定方法来改变 this 的值:(然而这仅仅是显式绑定)

                    想要详细了解:this四大绑定方式

                    5.1 call 方法

                    call 方法是 JavaScript 中函数的一个内建方法,允许你显式指定 this 的值,并立即调用函数。

                    语法:

                    func.call(thisArg, arg1, arg2, ...);
                    thisArg:指定函数执行时的 this 值。
                    arg1, arg2, ...:传递给函数的参数列表。
                    

                    示例:

                    function greet(name) {
                      console.log(`Hello, ${name}! My name is ${this.name}.`);
                    }
                    const person = { name: 'Alice' };
                    greet.call(person, 'Bob');  // 输出: Hello, Bob! My name is Alice.
                    

                    解释:在 call 中,this 被设置为 person 对象,因此 this.name 为 Alice。

                    function greet() {
                      console.log(this.name);
                    }
                    const person = { 
                    name: 'Alice'
                     };
                    greet.call(person); // 输出 'Alice'
                    

                    5.2 apply 方法

                    apply 与 call 类似,只是它接收参数的方式不同

                    ①基本语法

                    参数:

                    第一个参数:指定 this 的值(与 call() 一样,决定函数内部 this 的指向)。

                    第二个参数:是一个数组或者类数组对象,它包含了要传递给函数的多个参数。传递的是数组的元素 , 要明确细节概念

                    基本语法:

                    functionName.apply(thisArg, [arg1, arg2, ...]);
                    
                    • thisArg:表示我们希望 this 指向的对象。如果是null 意味着不改变this
                    • [arg1, arg2, …]:一个数组或者类数组对象,包含要传递给函数的多个参数
                      greet.apply(person); // 输出 'Alice'
                      
                      ②基础应用:求数组最值
                      Math.max函数可以求出一些数字的最大值 但是参数只能是数字 , 不能是数组
                      如果想要求数组最大值 , 那就用展开运算符 
                      var arr=[1,2,3]
                      console.log(Math.max(...arr))
                      然后转成数组就可以了 
                      但是需要注意一个问题 展开运算符其实是ES6新添的 那Math.max函数在此之前只能是求一堆数字的最大值 , 功能有些鸡肋 , 那么当时的程序员是如何使用Math.max来最大值的呢 ?
                      console.log(Math.max.apply(null,arr));
                      第一个参数是空意味着不改变this . 把数组的元素作为了实参列表 
                      等同于:
                      Math.max(arr[0], arr[2], arr[3])
                      

                      5.3 bind 方法

                      ①引子
                          按钮 
                          
                      class HomePage{ n=1; constructor (){ let box=document.querySelector("#box") box.innerHTML=this.n let btn=document.querySelector("#btn") let that=this; //this 指向事件触发的元素,也就是按钮 btn。而不是 HomePage 类的实例。 // 如果直接使用 this.n++,会报错,因为 btn 元素并没有 n 属性。只有this有 //为了解决这个问题,我们使用了 that = this;, //使得 that 保持了 constructor 中 this(即 HomePage 类的实例) 的引用。 btn.onclick=function(){ console.log(this); that.n++; box.innerHTML=that.n } } } new HomePage()
                      ②基本用法

                      bind 方法与 call 和 apply 不同,它返回一个新的函数,该函数的 this 值绑定到指定的对象。

                      const boundGreet = greet.bind(person);
                      boundGreet(); // 输出 'Alice'
                      //通过 bind() 创建了一个新的函数 boundGreet,这个新函数的 this 永久绑定为 person 对象。
                      

                      06类中的 this

                      在类的实例方法中,this 指向实例对象:

                      class Animal {
                        constructor(name) {
                          this.name = name;
                        }
                        
                        speak() {
                          console.log(`${this.name} makes a sound.`);
                        }
                      }
                      const dog = new Animal('Dog');
                      dog.speak(); // Dog makes a sound.
                      

                      07. 总结

                      前端知识点---this的使用方法详解(Javascript)

                              1-构造函数内部-new的时候创建的对象
                              2-对象方法的内部-谁调用方法,方法this的就是谁
                              3-箭头函数-没有自己的this,跟外部环境一致
                              4-事件处理函数-内部的this的,指的是绑定事件的元素(谁给添加的事件,里面的this就是谁)
                              5-普通函数-匿名函数-全局中-this都是window--(严格模式下面,普通函数内部的this是undefined)
                      
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

相关阅读

目录[+]

取消
微信二维码
微信二维码
支付宝二维码