The answers probably work but why no prototype use? Is the align function going to perform different logic on every instance?
As Bergi pointed out; JavaScript uses prototype to inherit and it's better to define members on the prototype that don't change between instances:
Simply explained; prototype can be used to declare members/properties that won't change for an instance. If I declare an object named Person and person has 2 members: name and greet. Greet will output "Hello, I am [this.name]" so greet does not change between instances.
When I declare the greet method on Person prototype and then create thousands of Person instances (ben, jack, mary ....) they will all share only one greet
function. This saves memory and cpu time for object intialisation. Check out this link for more info: https://stackoverflow.com/a/16063711/1641941
The following link might help you understand what this
refers to in JavaScript. https://stackoverflow.com/a/19068438/1641941
function Svg() {
this.someInstanceValue=22;
}
Svg.prototype.align = function(value) {
if(value === 'left') return 0;
}
function Graph() {
// get Svg's instance properties
Svg.apply(this,arguments);
console.log('<text x="' + this.align('left') + '"></text>');
}
//inherit from Svg:
Graph.prototype=Object.create(Svg.prototype);
Graph.prototype.constructor=Graph;
graph = new Graph();
graph.align('left');
If you don't want to inherit from Svg but mix it in then you can still use prototype to mix in it's functions (and call Svg.apply to get needed instance members):
function mixin(source, target){
for(thing in source){
if(source.hasOwnProperty(thing)){
target[thing]=source[thing];
}
}
};
function Svg() {
this.someInstanceValue=22;
}
Svg.prototype.align = function(value) {
if(value === 'left') return 0;
}
function Graph() {
// get Svg's instance properties
Svg.apply(this,arguments);
console.log('<text x="' + this.align('left') + '"></text>');
}
//mix in Svg:
mixin(Svg.prototype, Graph.prototype)
graph = new Graph();
graph.align('left');