javascript - Am I violating the Object-Oriented encapsulation principle? -
i wondering whether correct way initialize object, requires random position , speed on map. not sure whether violating encapsulation principle object initializers this.x , thi.y calling warrior.choosex() , 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 suggestion.
encapsulation principle restricting parts of object (e.g. internal operations or fields shouldn't available outside of object). common understanding using accessors access fields.
javascript doesn't offer mechanism allow restricting access fields or methods. however, possible achieve using module pattern.
in example, fields , methods publicly available. argue don't use accessors (getter/setter pair x , y), personal point of view wouldn't benefit code in way. also, accessing variable through assignment operator , setter function can end being compiled same code jit (at least, that's happens in java). in statically typed languages, there number of reasons why using accessors might good, of them doesn't apply javascript.
tl;dr
your code fine.
Comments
Post a Comment