MST

星途 面试题库

面试题:JavaScript 中类与 this 在方法调用中的使用

假设有如下 JavaScript 代码: ```javascript class Animal { constructor(name) { this.name = name; } sayName() { console.log(`My name is ${this.name}`); } } const dog = new Animal('Buddy'); const sayNameFunction = dog.sayName; ``` 当执行 `sayNameFunction()` 时会发生什么?如何修改代码使得 `sayNameFunction()` 能够正确输出 `My name is Buddy`?
14.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 执行 sayNameFunction() 时发生的情况
    • 在 JavaScript 中,函数在调用时,this 的指向取决于函数的调用方式。当 sayNameFunction 被赋值为 dog.sayName 后,直接调用 sayNameFunction(),此时 this 指向全局对象(在浏览器环境中是 window,在 Node.js 环境中是 global),而不是 dog 对象。因为 globalwindow 上没有 name 属性,所以不会正确输出 My name is Buddy,在严格模式下可能会报错(thisundefined),在非严格模式下可能输出 My name is undefined
  2. 修改代码的方法
    • 使用 bind 方法
      class Animal {
          constructor(name) {
              this.name = name;
          }
          sayName() {
              console.log(`My name is ${this.name}`);
          }
      }
      const dog = new Animal('Buddy');
      const sayNameFunction = dog.sayName.bind(dog);
      sayNameFunction();
      
      bind 方法会创建一个新的函数,在这个新函数中,this 被绑定到 bind 方法传入的第一个参数,即 dog 对象。所以调用 sayNameFunction() 时,this 指向 dog,能正确输出 My name is Buddy
    • 使用箭头函数
      class Animal {
          constructor(name) {
              this.name = name;
          }
          sayName() {
              console.log(`My name is ${this.name}`);
          }
      }
      const dog = new Animal('Buddy');
      const sayNameFunction = () => dog.sayName();
      sayNameFunction();
      
      箭头函数没有自己的 this,它的 this 取决于外层作用域的 this。这里外层作用域中 this 指向 windowglobal,但箭头函数内部调用 dog.sayName()dog.sayName 中的 this 指向 dog,所以能正确输出 My name is Buddy