You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS Revealing Module Pattern公共方法访问this.input报错如何解决

问题解决方案

报错原因

核心问题是this指向丢失:你将内部txt对象的test方法直接赋值给返回的公共对象属性,当调用v.test()时,方法内的this指向的是你返回的公共对象{test: txt.test},而非内部的txt实例。公共对象上没有挂载input属性,因此this.input为undefined,调用val()方法就会抛出类型错误。

可行修复方案

下面是几种常用的无侵入修复方式:

方案1:绑定test方法的固定执行上下文

在暴露公共方法时用bind将test的this永久绑定到内部的txt实例:

var txtModule = (function(window,$){
    var txt = {
        topics:{},
        test:function(){
            console.log(this.input.val());
        },
        _init:function(){
            this._cacheDom();
        },
        _cacheDom:function(){
            this.input = $("input#c_input");
        },
    }
    txt._init();
    return {
        // 绑定this指向内部txt对象
        test : txt.test.bind(txt),
    }
});
var v = txtModule(window,$);
v.test();

方案2:闭包包装调用,手动指定执行逻辑

在暴露的公共方法内部直接调用txt的对应方法,完全不依赖this指向:

// 仅修改return部分即可
return {
    test : function(){
        return txt.test();
    }
}

方案3:修改test方法内部实现,不依赖this

直接在test方法内引用闭包作用域下的txt变量,完全规避this指向问题:

var txt = {
    topics:{},
    test:function(){
        // 直接访问闭包内的txt变量,不受调用上下文影响
        console.log(txt.input.val());
    },
    // 其余属性和方法保持不变
    _init:function(){
        this._cacheDom();
    },
    _cacheDom:function(){
        this.input = $("input#c_input");
    },
}

内容的提问来源于stack exchange,提问作者Susantha7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:57:03