I'm trying to understand prototypal inheritance in Javascript, but failing to apply to the following case. Any help would be appreciated.
I'm defining a constructor as follows:
var base = function() {
var priv = "private"; // Private
var publ = "public"; // Public through a getter/setter (below)
// The object to return
var f = {};
f.publ = function (new_val) {
if (!arguments.length) {
return publ;
}
publ = new_val;
return f;
};
return f;
};
With this constructor, I can create objects by calling base();
. These objects have a public method (publ).
Now, following the same structure, I would like to have a new constructor that creates objects that inherits from objects created by the "base constructor" defined above:
var myclass = function () {
// Other parameters defined here
var f = function () {
// publ is inherited
console.log(f.publ());
};
// Trying to set the prototype of f to the object created by "base()"
f.prototype = base();
// Other methods defined here
return f;
};
With f.prototype = base();
I want to make f inherit all the methods that are defined in the object returned by base()
, but trying to call f.publ complains because f doesn't have method publ
Any help in understanding what is going on would be welcome
M;