The following example is based off of Mike Bostock's reusable charts proposal.
Given two functions (bar()
and pie()
) which each generate a different kind of chart:
function bar() {
var width = 720, // default width
height = 80; // default height
function my() {
console.log('bar created: ' + width + ' ' + height);
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};
my.render = function() {
my();
return my;
};
return my;
}
function pie() {
var width = 720, // default width
height = 80; // default height
function my() {
console.log('pie created: ' + width + ' ' + height);
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};
my.render = function() {
my();
return my;
};
return my;
}
I can call these functions via a chaining method as such:
bar().width(200).render(); // bar created: 200 80
pie().height(300).render(); // pie created 720 300
Is there a way to code these where my getter and setter methods are the same? For instance, I plan on having the width()
functions in each of these be the exact same. How can I make the bar()
and pie()
functions inherit shared functions like width()
, height()
, render()
?