Question

I like the revealing module pattern. I will have private functions that I would like to make public and return them. But I may also have some local functions within my revealing module pattern that "return this"...

var player = function(){
//my local variable scope...

oplayer.damage = function(){
    if(!this.grace){
        this.shield--;
        if (this.shield == 0){
            return this;
        }
    }
};
      ...

      return {
      damage : oplayer.damage
      }
      }();

Is it ok to "return this" if I am explicitly returning something? (in context to using the revealing module pattern). If not, how can I transform my local function oplayer.damage to be used in a proper context? Thanks for any advice! I'm just trying to wrap my mind around the whole "return this" concept.

Was it helpful?

Solution

It should be fine, because "this" is contextual to execution. Because you're returning this on a public function which is part of the "cut down" object, then you'll only get the cut down object. So, I think what you're trying to do should be fine if you consider the following scenarios:

var test = function(){
   var pri = function(){
       console.log("Private");
   };

   var pub = function(){
       pri();
       console.log("pub");
       return this;
   }

   return {
       pub: pub
   };
}();

console.log(test.pri); //-> undefined
console.log(test.pub); //-> function(){…}
console.log(test.pub()); //-> "Private" "pub" [Object {…}]
console.log(test.pub().pri); //-> "Private" "pub" undefined

OTHER TIPS

Please first check out what the this keyword is, there is a good introduction at MDN.

Is it ok to "return this" if I am explicitly returning something?

Yes, of course. This is the default pattern for chainability of methods - everything returns the object it was called on. However, to rely on that you'd need to return it in every case, not only when the shields are down.

If this wasn't your aim, just use a normal return; statement (results in undefined as like as no return statement).

in context to using the revealing module pattern

It does absolutely not matter where you defined that function.

transform my function to be used in a proper context?

(I assume with "context" you refer to the this object here)

You can't really, the value of this always depends on the invokation of the function. Of course, you could .bind() the function to your player object or just directly only return player instead of this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top