javascript - Let prototype function have sub functions with inherited environment -
having prototype object various functions, canvas. typically this:
function canvaspain() { ... } canvaspaint.prototype.drawfoo = function(x, y) { this.ctx.moveto(x, y); ... }; i have functions paintgrid() have sub functions – being property based objects. (not sure how word this.) example:
canvaspaint.prototype.grid = function() { this.paint = function() { this.ctx.moveto(0, 0); // here this.rows should property of canvaspaint.prototype.grid() // , not canvaspaint() (var = 0; < this.rows; ++i) { ... paint lines } }; }; and being able example:
var cp = new cp(); // , in function: this.grid.rows = 10; this.grid.cols = 10; this.grid.paint(); reason make code cleaner. of use this:
function canvaspain(arg) { ... this.properties = {}; this.properties.fig1 = {a:123, b:111}; this.properties.grid = { rows = arg.rows; cols = arg.cols; live = 1; }; } canvaspaint.prototype.paintgrid = function() { this.ctx.clearrect(0, 0, this.width, this.height); this.ctx.moveto(0, 0); (var = 0; < this.properties.grid.rows; ++i) ... } canvaspaint.prototype.foo = function() { this.paintgrid(); } this not me. want rid of "properties" object , instead set properties relevant function if there one. rows , columns grid belongs function object grid.
my question how can structure in code such grid function can inherit properties of mother object?
if cp.grid = new cp.grid(); becomes independent object , looses this.cxt etc. if cp.grid.paint() without initiating new object fails not having function paint.
your paint() function needs access both canvaspain object own properties such rows , cols.
so, each new canvaspain object need create dedicated .grid property:
function canvaspain(arg) { // ... // generate grid object this.grid = function(p) { // return public interface return { paint: function() { p.ctx.moveto(0, 0); (var = 0; < this.rows; ++i) { //... paint lines } } }; }(this); } the p variable inside function points canvaspain instance.
var cp = new canvaspain(); cp.grid.rows = 10; cp.grid.cols = 10; cp.grid.paint();
Comments
Post a Comment