问题主要来自于在子类中调用action
时,出现了Cannot read properties of undefined (reading 'generateGitAPI')
的问题,拷了个简易版过来,实际版本与此类似,报的是this.generateGitAPI is not a function
,都是由下面的这种写法引起的
/*
* @Description: 封装install命令注册,继承自父类command
*/
/**
* @description: 通过Builder模式对各个command完成注册
*/
'use strict';
let cmd = {
action(fn) {
fn()
}
}
class Command {
constructor(instance) {
// Cannot read properties of undefined (reading 'generateGitAPI') || ...is not a function
cmd.action(this.action)
// 正常调用子类中的generateGitAPI,及searchGitAPI
// cmd.action(() => {
// this.action()
// })
}
get command() {
throw new Error('command must implements')
}
get description() {
throw new Error('description must implements')
}
get options() {
return []
}
get action() {
throw new Error('action must implements')
}
preAction() {
console.log('pre')
}
postAction() {
console.log('post')
}
}
class InstallCommand extends Command {
constructor() {
super()
}
get command() {
return 'install'
}
get description() {
return '下载项目'
}
get options() {
return []
}
async action() {
await this.generateGitAPI()
await this.searchGitAPI()
}
/**
* @description: 生成GitAPI
*/
async generateGitAPI() {
console.log('generateGitAPI')
}
/**
* @description: 在git进行搜索
*/
async searchGitAPI() {
console.log('searchGitAPI')
}
}
const comman = new InstallCommand()
以前老师说过,碰到this
之类的问题,等它执行时才能知道this
指向哪,但上面这个例子我依旧有些懵逼,请老师帮忙解答下疑问