TypeScript代码中begin_search提示非函数的问题排查请求
排查 "begin_search is not a function" 错误的常见原因及解决办法
先把你的代码片段补全(方便分析):
export class Step1{ constructor(){ this.begin_search(); this.results_ready(); } private begin_search():void { setTimeout(() => { Searchfield.show_searchfield() }, 100); $('.search_box_overlay').show() $('.search_box_overlay_top').show() if (gon.search['search_type'] == 'package') $('.search_box_overlay_top .package').show() else if (gon.search['search_type'] == 'hotel') $('.search_box_overlay_top .hotel').show() else $('.search_box_overlay_top .air').show() } private results_ready():void { // 假设这里是你的方法实现 } }
结合这段代码,报错“begin_search not a function”通常是下面几个原因导致的,一个个来排查:
1. this 指向跑偏了(最常见)
你在构造函数里调用 this.begin_search(),但如果 this 没有指向 Step1 的实例对象,自然找不到这个方法。比如把 Step1 当作事件回调直接传递,或者实例化时的上下文不对:
// 错误示例:直接把构造函数绑定到事件,this会指向触发事件的元素,而非Step1实例 document.querySelector('#some-btn').addEventListener('click', Step1);
解决办法:
- 确保正确实例化类,让
this牢牢绑定到实例:// 正常实例化 const step1 = new Step1(); // 如果是事件回调,用箭头函数包裹,或者提前绑定this document.querySelector('#some-btn').addEventListener('click', () => new Step1()); // 或者在构造函数里提前绑定方法的this(如果后续这个方法会被当作回调单独调用) constructor(){ this.begin_search = this.begin_search.bind(this); this.results_ready = this.results_ready.bind(this); this.begin_search(); this.results_ready(); }
2. TypeScript编译配置拖后腿了
如果你的 tsconfig.json 里 target 设置的是ES5这类旧版本,类的私有方法编译后的JS代码可能会有兼容性问题,导致方法没有正确挂载到实例上。
解决办法:
打开 tsconfig.json,把 target 改成ES6及以上版本:
{ "compilerOptions": { "target": "ES6", "module": "ESNext", "strict": true // 其他配置... } }
3. 代码没加载对或者有语法错误
- 要是你的
Step1类代码在DOM还没加载完就执行了,或者页面上有同名的变量/类覆盖了它,也会导致方法找不到。 - 另外你提供的代码里
begin_search结尾是...,如果实际代码里有语法错误(比如没闭合的大括号、漏了分号),会直接导致类定义失败,实例化时自然找不到方法。
解决办法:
- 把实例化代码放到DOM加载完成后执行:
document.addEventListener('DOMContentLoaded', () => { new Step1(); }); - 检查
begin_search方法的代码,确保语法完整,没有遗漏的括号或者语句。
4. 私有方法的写法问题?
你用了TypeScript的 private 修饰符,在类内部调用是完全合法的,TypeScript的私有是编译时检查,运行时JS里方法还是会挂载到实例上。但如果是用了ES的私有字段(#begin_search),那调用时必须加 #:
// 要是用了ES私有字段,得这么写 export class Step1{ #begin_search():void { // ...方法实现 } constructor(){ this.#begin_search(); // 调用时要加# } }
内容的提问来源于stack exchange,提问作者Balance
相关产品推荐
相关产品推荐

