0

I'm wondering what is the best way to access the obj variable in this example:

function Module() {


  $('foo').on('click', function() {
    if (obj.test === true) {
      // do something
    }
  })


  return {
     setObj: function(obj) {
       // what should I do
     }
  }
}

Is there a simple way to access obj in the click handler. I'm looking for the simplest way possible.

1 Answer 1

3

Declare obj where it is in scope to both functions:

function Module() {

  var obj;

  $('foo').on('click', function() {
    if (obj.test === true) {
      // do something
    }
  })


  return {
    setObj: function(_obj) {
      obj = _obj;
    }
  }
}

If Module is used as a constructor (with new), you could also us this:

function Module() {

  var self = this;

  $('foo').on('click', function() {
    if (self.obj.test === true) {
      // do something
    }
  })

}

Module.prototype.setObj = function ( obj ) {
    this.obj = obj;
};

Or with ES6:

function Module() {

  $('foo').on('click', _ => {
    if (this.obj.test === true) {
      // do something
    }
  })

}

Module.prototype.setObj = function ( obj ) {
    this.obj = obj;
};
Sign up to request clarification or add additional context in comments.

3 Comments

I was trying to avoid that, but it clearly seems to be the best solution
@julesbou Is there a specific reason why you were trying to avoid that? I added a couple of alternatives.
you're awesome, but I prefer functional style and avoid using this if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.