javascript - Updating properties of JS "class" based on other properties? -
i'm relatively new javascript , trying create simple physics engine game type project working on. in order this, created understand js equivalent of class can create new copies of each object want. problem want able update value such x position , have update things such x middle position (x center of object on screen). know possible using object literal , getter, want able create new objects @ realtime based on what's on screen , couldn't figure out how use make work. here's general idea of trying do:
var object = function (xpos, ypos, width, height) { this.xpos = xpos; this.ypos = ypos; function getxmid (xp) { return xp + width/2; } this.xmid = getxmid (this.xpos); function getymid (yp) { return yp + height/2; } this.ymid = getymid (this.ypos); } var ball = new object (10, 20, 50, 50); ball.xpos = 50; console.log (ball.xmid); // want output 75 instead of 45
you're changing 1 property, , expecting other properties update, unfortunately doesn't work way when properties hold primitive values.
you use setters , getters , function update other properties when set value
var object = function(xpos, ypos, width, height) { this._xpos = xpos; this._ypos = ypos; this.recalc = function() { this.xmid = getxmid(this.xpos); this.ymid = getymid(this.ypos); } object.defineproperty(this, 'xpos', { get: function() { return this._xpos; }, set: function(v) { this._xpos = v; this.recalc(); } }); object.defineproperty(this, 'ypos', { get: function() { return this._ypos; }, set: function(v) { this._ypos = v; this.recalc(); } }); function getxmid(xp) { return xp + width / 2; } function getymid(yp) { return yp + height / 2; } this.recalc(); } var ball = new object(10, 20, 50, 50); ball.xpos = 50; console.log (ball.xmid); // want output 75 instead of 45
Comments
Post a Comment