第48关:花式调用与 this 🎭

XP: 0/100
🦸‍♂️

JS队长

函数怎么调用决定了 this 是谁!这可是 JS 中最令人头秃的问题之一。

🐛

Bug捣蛋鬼

哈哈哈!我要把 this 指向全局 window,或者 undefined,让你找不到对象!👻

🦸‍♂️

JS队长

我有三大神器来锁定 this

  • 1. call(): 立即调用,参数逗号隔开。
  • 2. apply(): 立即调用,参数是数组。
  • 3. bind(): 不立即调用,返回一个绑定了新 this 的新函数。

🎮 操控台:改变 this 的指向

我们要借用 person 对象的方法,但是用在 hero 对象上!

const person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
const hero = {
  firstName: "Iron",
  lastName: "Man"
}
            
Waiting for command...