0

I have an object setup like the following:

var StartScreenLayer = cc.Layer.extend({
ctor: function () {
    this._super();
    // this function can call createBackground!
    this.createBackground();
},
callCreateBackgroundToo: function () {
   // I can call createBackground too!
   this.createBackground();
},
createBackground: function () {
});

How do I arrange it so that createBackground is private but other other objects cannot call something like screenLayer.createBackground() and throw a createBackground is undefined type error on the object?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Hamed Saadat
  • 429
  • 5
  • 8
  • 1
    Have a look at [JavaScript private methods](http://stackoverflow.com/questions/55611/javascript-private-methods). You may want to use `createBackground.call(this)` for some of the answers. – Volune Aug 25 '14 at 22:58
  • 1
    Hey I took a look at it and it looks like you have to jump through a bunch of hoops to get it to work. I just decided to use an existing convention which is prefixing the function with an underscore. – Hamed Saadat Aug 26 '14 at 00:11
  • 1
    Prefixing with underscore is indeed also a good and accessible solution. Just FYI other solutions [may not be that hard](https://gist.github.com/Volune/b843f6966a5ba224ed74) (but maybe not as accessible) – Volune Aug 26 '14 at 01:08
  • Oh wow I like your example 2! Add that as an answer and I'll accept it tomorrow. – Hamed Saadat Aug 26 '14 at 01:14

1 Answers1

0

Apparently the convention is to just prefix it with an underscore. But its just a convention so you can still call the "private" function.

The cocos2d library that I'm using does this so I guess I will too.

Edit:

Following Volune's suggestions I went with the following method:

var StartScreenLayer = cc.Layer.extend(function() {
  function callCreateBackgroundToo() {
     // I can call createBackground too!
     createBackground(this);
  }
  function createBackground() {
  }
  return {
    ctor: function () {
        this._super();
        // this function can call createBackground!
        createBackground.call(this);
    }
  }
}());
Hamed Saadat
  • 429
  • 5
  • 8