Reputation: 4135
So I think I'm going crazy here. I'm trying to use prototype in my code, so I will have a Layer object that will have a Figure Object that will have a _newFigure function.
Layer = function(){}
Layer.prototype.figure = function(){}
Layer.prototype.figure.prototype._newFigure = function(){
//(Creates new Figure)
}
What I'm expecting in pseudo-code:
[LayerObject]{
figure:{
_newFigure:function(){
//(Creates new Figure)
}
}
}
Now that, to me, would be the logical thing to do, but for some reason it doens't work. Do you now how can I achieve that? Keep in mind I'm using prototype for performance reasons.
-- thanks in advance --
UPDATE---------------------------------------------------------------------------------------
As Nick said "Why does Layer need to have a Figure on it's prototype? It seems like Layer and Figure our separate entities, and a Layer can have a Figure instance attached to it. Just a thought : )"
So, I've updated the code (now working)
Layer = function(){
this.figure = new figureHandler(this);
}
function figureHandler(layer){
this.layer = layer;
}
figureHandler.prototype._newFigure = function(){
//(Creates new Figure)
}
-- See ya! Thanks for your help :) --
Upvotes: 0
Views: 82
Reputation: 398
Would something like the following work for you?
Figure = function() {};
Layer = function() {};
Layer.prototype.figure = function() {
return new Figure();
};
It's a bit confusing to me why you would want an interface like layer.figure._newFigure
when layer.figure
could create a new figure object for you. Perhaps your use case just isn't clear enough to me.
EDIT: Based on the comment to my original response, I assume you mean something like this:
Figure = function(layer) {
this.layer = layer;
};
Layer = function() {};
Layer.prototype.figure = function() {
return new Figure(this);
};
Upvotes: 1
Reputation: 39360
I think you may be looking for something like this:
Figure has a Layer instance and a Layer instance has multiple figures. Layer may have a factory that will create Figures having the current Layer instance:
Layer = function Layer(){
this.figures = [];
};
Layer.prototype.addFigure = function addFigure(arg){
arg = arg || {};
arg.layer = this;
this.figures.push(new Figure(arg));
return this;//now you can stack functions
}
Figure = function Figure(arg){
arg = arg || {};
//layer is not optional
this.layer = arg.layer
|| (function(){
throw new Error('Cannot create figure without layer');
}());
this.shape = arg.shape || 'square';
}
var l = new Layer();
l.addFigure({shape:'round'})//stacking next addFigure on next line
.addFigure();//defaults to square
console.log(l.figures);
More info on constructor functions and prototype here: https://stackoverflow.com/a/16063711/1641941
Upvotes: 0