0

I was wondering whether this would be a correct way to initialize an object, which requires a random position and speed on the map. I am not sure whether I am violating the encapsulation principle with the object initializers this.x and thi.y by calling Warrior.chooseX() and Warrior.choosey(), respectively.

var Warrior = function() {
    this.x = Warrior.chooseX();
    this.y = Warrior.chooseY();
    this.speed = Warrior.chooseSpeed();
};

Warrior.chooseX = function() {
    return Math.random() * 600 - 200;
};

Warrior.chooseY = function() {
    var randomNumber = Math.random();

    if (0 <= randomNumber && randomNumber < 0.5) {
        return 100;
    } else {
        return 200;
    }
};

Warrior.chooseSpeed = function() {
    return Math.floor(Math.random() * 200) + 100;
};

var warrior = new Warrior();

Thanks for any suggestion.

Jose
  • 55
  • 4

1 Answers1

3

Encapsulation principle is about restricting some parts of an object (e.g. internal operations or fields that shouldn't be available from outside of the object). Common understanding is also using accessors to access fields.

Javascript doesn't offer any mechanism that allow restricting access to fields or methods. However, it is possible to achieve it by using Module pattern.

In your example, all fields and methods are publicly available. Some could argue that you don't use accessors (getter/setter pair for x and y), but my personal point of view is that it wouldn't benefit your code in any way. Also, accessing a variable through assignment operator and setter function can end up being compiled to exactly the same code by JIT (at least, that's what happens in Java). In statically typed languages, there are a number of reasons why using accessors might be good, but most of them doesn't apply to javascript.

tl;dr

Your code is fine.

Community
  • 1
  • 1