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

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736


this动态绑定 , this的用法

在JavaScript中,this 是一个非常重要但是呢 也让人难搞明白的关键字。
**它的值不是在编写代码时静态确定的,而是在代码运行时动态绑定的。**这非常重要
this 不是指向函数本身,而是指向 调用函数的对象。根据调用方式的不同,this 会指向不同的对象
下面讲一下它 .
01. 全局作用域下的 this

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

  1. console.log(this); // 浏览器中输出 Window
复制代码
② 在Node.js环境中,this 指向 global 对象

  1. console.log(this); // 在 Node.js 中输出:{} (指向 global 对象)
  2. function showThis() {
  3.     console.log(this); // 在 Node.js 中输出:{} (指向 global 对象)
  4. }
  5. showThis();
复制代码
③特殊阐明

在严格模式(‘use strict’)下,this 在全局作用域中将是 undefined,而不是 window 或 global。
  1. 'use strict';
  2. console.log(this); // 在严格模式下输出:undefined
复制代码
02. 函数中的 this

this 在函数中的举动取决于调用的方式。
2.1 普通函数和匿名函数调用

当函数以普通方式调用时,this 默认指向全局对象(在严格模式下是 undefined)。
  1. function foo() {
  2.   console.log(this);
  3. }
  4. foo(); // 浏览器中,this 指向 window
复制代码
  1. //   匿名函数
  2.       setTimeout(function () {
  3.         console.log(this); //window
  4.       }, 1000);
  5.       console.log(this); //window
复制代码
在严格模式下:
  1. "use strict";
  2. function foo() {
  3.   console.log(this);
  4. }
  5. foo(); // undefined
复制代码
2.2 构造函数和调用

当一个函数用作构造函数(通过 new 关键字调用 创建一个新的对象实例,并将该对象与构造函数绑定)时,this 指向新创建的实例对象(关键) , 用于将属性和方法绑定到该对象。
  1. function Person(name) {
  2. //创建一个构造函数 , 参数为name
  3.   this.name = name;//this指向当前创建的实例对象 , 新对象有个名为name的属性 this.name = name; 将参数 name 的值赋给对象的 name 属性。
  4. }
  5. const person = new Person('Bob');
  6. console.log(person.name); // 输出 'Bob'
  7. function Person(name, age) {
  8.   this.name = name; // this 绑定到新创建的对象
  9.   this.age = age;
  10. }
  11. const person1 = new Person('Alice', 25);
  12. console.log(person1); // Person { name: 'Alice', age: 25 }
  13. function Car(brand, model) {
  14.   this.brand = brand; // 将 brand 绑定到新对象
  15.   this.model = model; // 将 model 绑定到新对象
  16.   this.getDetails = function() {
  17.     return `${this.brand} ${this.model}`;
  18.   };
  19. }
  20. const car1 = new Car('Toyota', 'Corolla');
  21. console.log(car1.getDetails()); // Toyota Corolla
复制代码
2.3 箭头函数中的 this

箭头函数不会创建自己的 this,它会继承来自其界说位置的外层上下文的 this。
  1. const obj = {
  2.   name: 'Alice',
  3.   arrowFunc: () => {
  4.     console.log(this.name);
  5.   }
  6. };
  7. obj.arrowFunc(); // undefined, 因为箭头函数中的 this 绑定的是全局对象
  8. 而普通函数会绑定到调用它的对象:
  9. const obj = {
  10.   name: 'Alice',
  11.   normalFunc: function() {
  12.     console.log(this.name);
  13.   }
  14. };
  15. obj.normalFunc(); // 输出 'Alice'
  16. 使用箭头函数时,this 会继承自外层作用域:
复制代码
03对象方法调用

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

函数作为对象的方法调用时,this 指向调用该方法的对象。
  1. const obj = {
  2.   name: 'Alice',
  3.   sayName: function() {
  4.     console.log(this.name);//this 指向调用该方法的对象,即 obj
  5.   }// 应该是一个方法 是函数类型的方法
  6. };
  7. obj.sayName(); // 输出 'Alice'
复制代码
② this 在对象的方法中使用

this 在对象的方法中使用时,this 指向调用该方法的对象。
  1. const obj = {
  2.   name: 'Alice',
  3.   getName() {
  4.     return this.name;
  5.   }
  6. };
  7. console.log(obj.getName()); // 输出 "Alice"
复制代码
③赋值

  1. const obj1 = {
  2.   name: "Bob",
  3.   greet: function() {
  4.     console.log(this.name);
  5.   }
  6. };
  7. const obj2 = {
  8.   name: "Charlie"
  9. };
  10. obj2.greet = obj1.greet;// 将 obj1 的 greet 方法赋给 obj2
  11. obj2.greet(); // "Charlie"
复制代码
只管 greet 方法最初是界说在 obj1 上,但当我们将 greet 赋值给 obj2 后,调用 obj2.greet() 时,this 就指向了 obj2,而不是 obj1
04. 变乱处理中的 this(变乱处理函数)

在变乱处理函数中,this 通常指向触发变乱的 DOM 元素。
  1. <button>别点我<button>
复制代码
  1. const button = document.querySelector('button');
  2. button.addEventListener('click', function() {
  3.   console.log(this); // 输出被点击的按钮元素
  4. });
复制代码

05. 动态绑定的方式

为什么要改变this的呢? 由于知道this的值一般不是我们想要的 , 比如箭头函数, 它没有自己的this . 以是下面讲一下 , 如何改变this的值 .
JavaScript 提供了三种显式绑定方法来改变 this 的值:(然而这仅仅是显式绑定)
想要详细了解:this四大绑定方式
5.1 call 方法

call 答应你显式指定 this 的值,并立刻调用函数。
call的语法 functionName.call(thisArg, arg1, arg2, …);
  1. function greet() {
  2.   console.log(this.name);
  3. }
  4. const person = {
  5. name: 'Alice'
  6. };
  7. greet.call(person); // 输出 'Alice'
复制代码
5.2 apply 方法

apply 与 call 雷同,只是它吸收参数的方式不同
①根本语法

参数:
第一个参数:指定 this 的值(与 call() 一样,决定函数内部 this 的指向)。
第二个参数:是一个数组或者类数组对象,它包罗了要传递给函数的多个参数。传递的是数组的元素 , 要明白细节概念
根本语法:
  1. functionName.apply(thisArg, [arg1, arg2, ...]);
复制代码


  • thisArg:表示我们希望 this 指向的对象。假如是null 意味着不改变this
  • [arg1, arg2, …]:一个数组或者类数组对象,包罗要传递给函数的多个参数
  1. greet.apply(person); // 输出 'Alice'
复制代码
②底子应用:求数组最值

  1. Math.max函数可以求出一些数字的最大值 但是参数只能是数字 , 不能是数组
  2. 如果想要求数组最大值 , 那就用展开运算符
  3. var arr=[1,2,3]
  4. console.log(Math.max(...arr))
  5. 然后转成数组就可以了
  6. 但是需要注意一个问题 展开运算符其实是ES6新添的 那Math.max函数在此之前只能是求一堆数字的最大值 , 功能有些鸡肋 , 那么当时的程序员是如何使用Math.max来最大值的呢 ?
  7. console.log(Math.max.apply(null,arr));
  8. 第一个参数是空意味着不改变this . 把数组的元素作为了实参列表
  9. 等同于:
  10. Math.max(arr[0], arr[2], arr[3])
复制代码
5.3 bind 方法

①引子

  1. <body>
  2.     <button id="btn">按钮 </button>
  3.     <div id="box"></div>
  4. </body>
  5. </html>
  6. <script>
  7. class HomePage{
  8.     n=1;
  9.   constructor (){
  10.    
  11.     let box=document.querySelector("#box")
  12.     box.innerHTML=this.n
  13.     let btn=document.querySelector("#btn")
  14.     let  that=this;
  15.    
  16. //this 指向事件触发的元素,也就是按钮 btn。而不是 HomePage 类的实例。
  17. // 如果直接使用 this.n++,会报错,因为 btn 元素并没有 n 属性。只有this有
  18. //为了解决这个问题,我们使用了 that = this;,
  19. //使得 that 保持了 constructor 中 this(即 HomePage 类的实例) 的引用。
  20.     btn.onclick=function(){
  21.         console.log(this);
  22.         that.n++;
  23.         box.innerHTML=that.n
  24.         
  25.     }
  26.   }
  27. }
  28. new HomePage()
  29. </script>
复制代码
②根本用法

bind 方法与 call 和 apply 不同,它返回一个新的函数,该函数的 this 值绑定到指定的对象。
  1. const boundGreet = greet.bind(person);
  2. boundGreet(); // 输出 'Alice'
  3. //通过 bind() 创建了一个新的函数 boundGreet,这个新函数的 this 永久绑定为 person 对象。
复制代码
06类中的 this

在类的实例方法中,this 指向实例对象:
  1. class Animal {
  2.   constructor(name) {
  3.     this.name = name;
  4.   }
  5.   
  6.   speak() {
  7.     console.log(`${this.name} makes a sound.`);
  8.   }
  9. }
  10. const dog = new Animal('Dog');
  11. dog.speak(); // Dog makes a sound.
复制代码
07. 总结


  1.         1-构造函数内部-new的时候创建的对象
  2.         2-对象方法的内部-谁调用方法,方法this的就是谁
  3.         3-箭头函数-没有自己的this,跟外部环境一致
  4.         4-事件处理函数-内部的this的,指的是绑定事件的元素(谁给添加的事件,里面的this就是谁)
  5.         5-普通函数-匿名函数-全局中-this都是window--(严格模式下面,普通函数内部的this是undefined)
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

尚未崩坏

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表