reference - javascript setting attribute of prototype to attribute of object -


to begin with, don't understand prototypal structure of javascript may not possible.

if have ...

var vector = function( x, y ) {     this.x = x || 0;     this.y = y || 0; }  var obj = function() {     this.position = new vector( 0, 0, 0 ); }  var cube = new obj(); 

... how can add property x obj such calling cube.x equivalent cube.position.x. think should possible make properties of each reference same value, i'm not sure of syntax. obj.prototype.x = obj.position.x doesn't work because obj.position undefined.

i following behaviour possible

alert(cube.position.x); // 0 alert(cube.x); // 0  cube.position.x = 2; alert(cube.position.x); // 2 alert(cube.x); // 2  cube.x = 4; alert(cube.position.x); // 4 alert(cube.x); // 4 

is possible?

i should mention i'm working three.js rewriting objects isn't option, adding them , prototypes.

to cube.x return whatever cube.position.x contains, you'd need define accessors , mutators obj.prototype.x. accessors , mutators relatively newer feature in javascript, , not supported in versions of ie.

var vector = function( x, y ) {     this.x = x || 0;     this.y = y || 0; }  var obj = function() {     this.position = new vector( 0, 0, 0 ); } obj.prototype = {     ...your prorotype methods here... }; object.defineproperty(obj.prototype, 'x', {     get: function () {         return this.position.x;     },     set: function (val) {         this.position.x = val;     } });  //alternatively: obj.prototype = {     x() {         return this.position.x;     },     set x(val) {         this.position.x = val;     } };  var cube = new obj(); cube.x; //0 cube.x = 10; cube.position.x; //10 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -