开发者

Cant understand scope issue here

I dont understand why/ how to accomplish this fairly simple thing. If someone could explain it that would be great.

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
  }
}

How do I access Collapse inside this function? Or should these work and perhaps i have something else wrong?


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
  }
}


Assuming you're calling Module as a constructor, you could make EnableCollapse a property of the object rendered.

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();

Otherwise, if you intend to keep EnableCollapse private, you manually set its this value.

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

    function EnableCollapse() {

        this.host.Collapse.hide();
    }

    EnableCollapse.call(this);
}

Ultimately, the value of this will depend on how you're calling Module and Collapse.


You access Collapse inside the function via this.host.Collapse

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜