MST

星途 面试题库

面试题:JavaScript 类的继承与 this 绑定问题

考虑以下 JavaScript 类继承结构: ```javascript class Shape { constructor() { this.x = 0; this.y = 0; } move(dx, dy) { this.x += dx; this.y += dy; console.log(`Moved to (${this.x}, ${this.y})`); } } class Rectangle extends Shape { constructor(width, height) { super(); this.width = width; this.height = height; } draw() { console.log(`Drawing rectangle at (${this.x}, ${this.y}) with width ${this.width} and height ${this.height}`); } } ``` 如果有 `const rect = new Rectangle(10, 20);`,然后 `const moveFunction = rect.move.bind({x: 100, y: 100});`,当调用 `moveFunction(5, 5)` 后,再调用 `rect.draw()`,输出是什么?为什么?如何确保 `rect.draw()` 输出正确的位置信息?
45.9万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 输出内容
    • 调用 moveFunction(5, 5) 后,再调用 rect.draw() 的输出是 Drawing rectangle at (0, 0) with width 10 and height 20
  2. 原因
    • const moveFunction = rect.move.bind({x: 100, y: 100}); 这里使用 bind 方法创建了一个新函数 moveFunction,并将其 this 绑定到了 {x: 100, y: 100} 这个对象上。
    • 当调用 moveFunction(5, 5) 时,实际修改的是 {x: 100, y: 100} 这个对象的 xy 属性,而不是 rect 对象的 xy 属性。rect 对象的 xy 属性仍然保持初始值 0
    • 所以当调用 rect.draw() 时,输出的位置信息是 (0, 0)
  3. 确保 rect.draw() 输出正确位置信息的方法
    • 不使用 bind 改变 rect.movethis 指向。如果需要对 rect 进行移动操作,直接调用 rect.move(5, 5),这样 rect 对象的 xy 属性会被正确修改,后续调用 rect.draw() 就能输出正确的位置信息。
    • 如果一定要使用 bind 来创建一个新函数,可以在 bind 时绑定 rect 自身,例如 const moveFunction = rect.move.bind(rect);,这样调用 moveFunction(5, 5) 就会修改 rect 对象的 xy 属性,rect.draw() 也能输出正确位置。