Zholen
Zholen

Reputation: 1790

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?

Upvotes: 1

Views: 60

Answers (3)

vol7ron
vol7ron

Reputation: 42099

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

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

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

Upvotes: 3

user113716
user113716

Reputation: 322462

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.

Upvotes: 2

Related Questions