学习笔记:类中的方法this指向问题

36 阅读1分钟

问题

类中的方法默认开启了局部的严格模式,若该方法不是实例对象调用的,那么输出的this将会是undefined

    class Person {
        constructor(name, age) {
            this.name = name,
            this.age = age
        }
        speak() {
            // 'use strict' 此行代码默认执行
            console.log(`My name is ${this.name}`)
        }
        
    }
    const p1 = new Person('Joshua', 18);
    p1.speak(); // Output: Joshua
    
    // 将speak方法赋值给x
    const x = p1.speak;
    // 由window调用speak方法
    x(); // TypeError: Cannot read properties of undefined

解决方案

在constructor中使用Function.prototype.bind()

bind():bind()  方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

    class Person {
        constructor(name, age) {
            this.name = name,
            this.age = age
            this.speak = this.speak.bind(this) // 将原型上的speak方法赋值给实例对象上的speak方法
        }
        speak() {
            // 'use strict' 此行代码默认执行
            console.log(`My name is ${this.name}`)
        }
        
    }
    const p1 = new Person('Joshua', 18);
    p1.speak(); // Output: Joshua
    
    const x = p1.speak;
    x(); // Output: Joshua