Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 6 years ago

Encapsulation with JavaScript?

Is it possible to instantiate a JavaScript object with a constructor, but also prevent all its properties from being accessed directly (like how its done in C/Java) ?

var game = new Game(xArg, yArg);

game.x = 3; // should not work or cause an error

console.log(game.y); // should not work or cause an error

The closest I've found to doing this is with the revealing module pattern, but some properties will be accessible directly.

2 Answers

Relevance
  • 6 years ago
    Favorite Answer

    The revealing module pattern is one way to do it. What do you mean by "but some properties will be accessible directly"? Do you mean that the revealing module pattern will still have some accessible properties, or that you want to make some properties of your object accessible?

    An example:

    function Game(xArg, yArg) {

        var x = xArg;

        var y = yArg;

        var getX = function() { return x; };

        var getY = function() { return y; };

        return {

            getX : getX,

            getY : getY

        };

    };

    var game = new Game(1, 2);

    console.log(game.getX()); // outputs 1

    console.log(game.x); // outputs undefined

    The problem with JavaScript in this case is that you can set any property to any object directly, which is not what you may intend.

    var game = new Game(1, 2);

    game.x = 5; // will go through, but doesn't affect the private x inside game

    console.log(game.getX()); // outputs 1

    console.log(game.x); // outputs 5

    As you can see, if you still use game.x in your code, it'll give you the wrong value. This is pretty much unavoidable, so just make sure you always use getX() instead.

  • God
    Lv 7
    6 years ago

    function MyObject(a) {

    this.visibleA = a;

    var invisibleA = a;

    }

    function test() {

    var myObject = new MyObject("test");

    alert(myObject.visibleA);

    alert(myObject.invisibleA);

    }

Still have questions? Get your answers by asking now.