How can I use this "public" method correctly?

I have this code (JSFiddle)

var OBJ = function(){
    var privateVar = 23;
    var self = this;

    return {
        thePrivateVar : function() {
          return privateVar;
        },  

        thePrivateVarTimeout : function() {
            setTimeout(function() { alert(self.thePrivateVar()); } , 10);
        }
    }

}();

alert(OBJ.thePrivateVar());

OBJ.thePrivateVarTimeout();

This is an abstraction of the real problem that I am facing.

So - I would expect the call OBJ.thePrivateVarTimeout()to wait 10, and then alertfrom 23 (which I want to get through another public method).

However self, it does not seem to work correctly. When I install self = this, it seems that thisit is not a function reference, but a reference to a global object. Why is this?

How to make a public method thePrivateVarTimeoutcall another public method thePrivateVar?

+5
source share
1 answer
var OBJ = (function(){
    var privateVar = 23;
    var self = {
        thePrivateVar : function() {
          return privateVar;
        },  

        thePrivateVarTimeout : function() {
            setTimeout(function() { alert(self.thePrivateVar); } , 10);
        }
    };

    return self;

}());

this === global || undefined . ES5 , ES5 undefined.

var that = this

var obj = (function() {
  var obj = {
    property: "foobar",
    timeout: function _timeout() {
      var that = this;
      setTimeout(alertData, 10);

      function alertData() {
        alert(that.property);
      }
    }
  }

  return obj;
}());

.bindAll

var obj = (function() {
  var obj = {
    alertData: function _alertData() {
      alert(this.property);
    }
    property: "foobar",
    timeout: function _timeout() {
      setTimeout(this.alertData, 10);
    }
  }

  bindAll(obj)

  return obj;
}());


/*
    bindAll binds all methods to have their context set to the object

    @param Object obj - the object to bind methods on
    @param Array methods - optional whitelist of methods to bind

    @return Object - the bound object
*/
function bindAll(obj, whitelist) {
    var keys = Object.keys(obj).filter(stripNonMethods);

    (whitelist || keys).forEach(bindMethod);

    function stripNonMethods(name) {
        return typeof obj[name] === "function";
    }

    function bindMethod(name) {
        obj[name] = obj[name].bind(obj);
    }

    return obj;
}
+5

All Articles