class类在实例化的constructor过程中可以使用其原型方法的

如题,今天特意测试了下类在执行constructor方法中是否可以使用其原型方法,测试文件内容如下:

class Test {
    constructor() {
        const names = Object.getOwnPropertyNames(Test.prototype)
        console.log('names:', names)
        this.name = '章三'
        setTimeout(this.getName.bind(this), 1000)

        console.log('ddd:', this.getName)
        this.getName()
        this.init()
    }

    init() {
        console.log('init')
        this.getName()
    }

    getName() {
        console.log('name:', this.name)
    }
}
new Test()

这是console的输出结果:

names: [ 'constructor', 'init', 'getName' ]
ddd: getName() {
        console.log('name:', this.name)
    }
name: 章三
init
name: 章三
name: 章三

也即:在创建类的实例过程中,类的constructor方法可以访问类的原型上的方法:两种情形,一是可以调用类的原型上的方法,二是类的原型方法可以作为回调函数使用,比如例子中的setTimeout部分

猜你喜欢

转载自blog.csdn.net/ccaoee/article/details/81633798
今日推荐