Javascript 我不能理解这里的范围问题

Javascript 我不能理解这里的范围问题,javascript,Javascript,我不明白为什么/如何完成这件相当简单的事情。如果有人能解释,那就太好了 function Module(config) { this.host = {Collapse: $('<a href="#" class="collapse">C</a>')}; function EnableCollapse() { //I need to access host.Collapse here this.host.Collapse.hide(); // Th

我不明白为什么/如何完成这件相当简单的事情。如果有人能解释,那就太好了

function Module(config) {
  this.host = {Collapse: $('<a href="#" class="collapse">C</a>')};

  function EnableCollapse() {
    //I need to access host.Collapse here
    this.host.Collapse.hide(); // Throws error
    host.Collapse.hide(); //Throws error
  }
}
功能模块(配置){
this.host={Collapse:$('')};
函数enableClapse(){
//我需要访问主机。在这里崩溃
this.host.Collapse.hide();//抛出错误
host.Collapse.hide();//抛出错误
}
}

如何访问此函数内部的折叠?或者这些都可以工作,也许我出了什么问题?

假设您作为构造函数调用
模块
,您可以将
启用塌陷
作为渲染对象的属性

function Module(config) {
    this.host = {
        Collapse: $('<a href="#" class="collapse">C</a>')
    };

    this.EnableCollapse = function () {

        this.host.Collapse.hide();
    }
}

var mod = new Module({...});

mod.EnableCollapse();

最终,
的值将取决于调用
模块
折叠
的方式。假设您作为构造函数调用
模块
,则可以将
启用折叠
作为渲染对象的属性

function Module(config) {
    this.host = {
        Collapse: $('<a href="#" class="collapse">C</a>')
    };

    this.EnableCollapse = function () {

        this.host.Collapse.hide();
    }
}

var mod = new Module({...});

mod.EnableCollapse();
function Module(config) {
  var that = this;
  that.host = {Collapse: $('<a href="#" class="collapse">C</a>')};

  function EnableCollapse() {
    //I need to access host.Collapse here
    that.host.Collapse.hide(); // Throws error
  }
}
最终,
的值将取决于您调用
模块
折叠
函数模块(配置)的方式{
function Module(config) {
  var that = this;
  that.host = {Collapse: $('<a href="#" class="collapse">C</a>')};

  function EnableCollapse() {
    //I need to access host.Collapse here
    that.host.Collapse.hide(); // Throws error
  }
}
var=这个; that.host={Collapse:$('')}; 函数enableClapse(){ //我需要访问主机。在这里崩溃 that.host.Collapse.hide();//抛出错误 } }
功能模块(配置){
var=这个;
that.host={Collapse:$('')};
函数enableClapse(){
//我需要访问主机。在这里崩溃
that.host.Collapse.hide();//抛出错误
}
}

您通过
this.host.Collapse

访问函数内部的折叠
您通过
this.host.Collapse

访问函数内部的折叠
您如何执行
启用折叠
功能?您如何执行
启用折叠
功能?谢谢,我理解我现在所做的不同!我将如何混合公共和私人功能?例如,我想让一个私有函数在实例化调用保持公共的EnableCollapse的对象时被调用?@Zholen:您可以创建一个对
this
(在模块中)的外部值的引用,如另一个答案所示,或者在调用私有函数时,使用
.call
手动设置其
this
值,然后只需从内部调用
this.enableClopse()
<代码>函数privateFunc(){/*dou_something*/this.enableclapse();}privateFunc.call(this)谢谢,我理解我现在所做的不同!我将如何混合公共和私人功能?例如,我想让一个私有函数在实例化调用保持公共的EnableCollapse的对象时被调用?@Zholen:您可以创建一个对
this
(在模块中)的外部值的引用,如另一个答案所示,或者在调用私有函数时,使用
.call
手动设置其
this
值,然后只需从内部调用
this.enableClopse()
<代码>函数privateFunc(){/*dou_something*/this.enableclapse();}privateFunc.call(this)