如何从jQuery作用域调用同一类中的类成员方法?
解决jQuery回调中调用类方法的上下文问题
你遇到的问题核心是上下文丢失:在jQuery对话框的按钮回调函数里,this指向的是当前按钮对应的DOM元素(或者对话框容器),而不是你的displayTemplate类实例,所以自然找不到findWithAttr方法。下面给你三种常用的解决办法:
方法1:提前保存类实例的上下文
在router方法里先把类实例的this存到一个变量里(比如self或者that),然后在回调里用这个变量调用方法:
class displayTemplate{ findWithAttr(action) { /* 你的逻辑 */ } router(action){ // 提前保存类实例的this const self = this; if(action == "something"){ $( "#confirm_dialog_msg" ).text("text?"); $( "#dialog-confirm" ).dialog({ buttons: { "yes": function() { $( this ).dialog( "close" ); // 用保存的self调用类方法 self.findWithAttr(action); }, "No": function() { /* 你的逻辑 */ } } }); } //... } }
方法2:使用箭头函数(ES6+)
箭头函数不会创建自己的上下文,它会继承外层作用域的this,也就是router方法里的类实例this,这样直接调用就没问题:
class displayTemplate{ findWithAttr(action) { /* 你的逻辑 */ } router(action){ if(action == "something"){ $( "#confirm_dialog_msg" ).text("text?"); $( "#dialog-confirm" ).dialog({ buttons: { "yes": () => { // 注意:箭头函数里的this不是对话框元素,所以要换方式关闭对话框 $( "#dialog-confirm" ).dialog( "close" ); // 直接用this调用类方法,此时this是类实例 this.findWithAttr(action); }, "No": function() { /* 你的逻辑 */ } } }); } //... } }
⚠️ 提示:用箭头函数的话,回调里的this不再指向对话框元素,所以关闭对话框时不能用$(this).dialog("close"),得直接通过选择器$("#dialog-confirm")操作,或者提前把对话框元素存到变量里。
方法3:用bind绑定上下文
把回调函数的this绑定到类实例上,这样回调里的this就会指向类实例:
class displayTemplate{ findWithAttr(action) { /* 你的逻辑 */ } router(action){ if(action == "something"){ $( "#confirm_dialog_msg" ).text("text?"); $( "#dialog-confirm" ).dialog({ buttons: { "yes": function() { $( this ).dialog( "close" ); // 此时this是类实例 this.findWithAttr(action); }.bind(this), // 绑定类实例的this到回调函数 "No": function() { /* 你的逻辑 */ } } }); } //... } }
这种方法的好处是,回调里的this既指向类实例(可以调用类方法),如果要操作按钮/对话框元素,还能通过event.currentTarget获取当前按钮DOM节点。
内容的提问来源于stack exchange,提问作者evarc
相关产品推荐
相关产品推荐

