1

I'm modifying a module for a game that we are developing and it is built with ImpactJS game engine. What we wanted to do is to make the variables private or inaccessible to other classes.

For example:

this.object.variable = 100; // Not okay.
this.object.setVariable( 100 ); // Okay.

ig.module( 
    'game.data.server' 
).requires(

).defines(function(){

    ServerData = ig.class.Extend({
        _variable : -1,

        get variable() {
            return this._variable ;
        },
        setVariable: function( value ) {
            this._variable = value;
        }
    });
});

But JavaScript setter and getter return different outputs

We can't do several revisions because this is also accessed by other games that we are developing.

Is there a better solution?

Community
  • 1
  • 1
benjtupas
  • 610
  • 9
  • 25

1 Answers1

2

First possibility

You could try doing this but as I haven't developed anything using ImpactJS it may not work as expected as it depends what the .class.extend() function does internally.

But it's worth a try.

var ServerData = ig.class.Extend((function() {
    var privateVar = -1;
    return {
        getVariable: function() {
            return privateVar;
        },
        setVariable: function(value) {
            privateVar = value;
        }
    };
})());

This code may seem a bit confusing to you, but what I've changed I've created an immediately executing function to create a function closure, which is required to create private space in which I created private to closure variable that's not visible outside.

I would suggest you to read Douglas Crockford's Javascript and learn even more stuff about the language you're using.

Second possibility

According to link in comments it seems that we can use define's closure for private members as well:

var privateVar = -1;

var ServerData = ig.class.Extend({
    getVariable: function() {
        return privateVar;
    },
    setVariable: function(value) {
        privateVar = value;
    }
});
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • 1
    Here is a question from the ImpactJS forums (http://impactjs.com/forums/help/entity-coding-convention) that sites some code that someone else had seen that leveraged closures to create private members. In their example they var them inside the defines but before the Extend. Your example would would as well (at least in as much as I understand closures and JavaScript) – Jason Sperske May 08 '14 at 05:56
  • @JasonSperske: Yes `.define` already creates a function closure, but OP's using literal object to extend internal class definition and I've created a closure there as I said I don't know the inner working of the `.extend` function. According to your link it seems one can use define's closure for private members. Let me edit my answer with the same. – Robert Koritnik May 08 '14 at 05:59