I have the following code:
var defaults = {
test: function () {
alert('Test');
}
};
function Foo(options) {
o = $.extend({}, defaults, options);
Foo.prototype.test = o.test;
}
Foo.prototype.test = defaults;
I want that the test method should be extensible and I want it to be used as:
var f = new Foo({
test: function() {
alert('Test2');
}
});
var f1 = new Foo({
test: function () {
alert('Test3');
}
});
f.test();//alert(test2) should be called
f1.test(); //alert(test3) should be called
Edit: I am not getting what I have written in the comments as the output.
You’re kind of mixing metaphors there. Three options for you:
Functional
It sounds like you’d like the form of functional inheritance that Douglas Crockford likes, which does away with prototypes in favor of what he calls “maker” functions:
…where
makeFoois:Live example | source
I’m not a huge fan of it myself, but there are many who are and certainly like most things, it has advantages and disadvantages. One of the advantages is how simple it is.
Simple constructor functions, override per instance
But you can do it with constructor functions, much as you tried; you apply the options to
thisrather than creating your own separate object:Live example | source
Reusable prototypical inheritance
If you want to go further and have proper hierarchies based on prototypical inheritance (so you can create more than one object with a specific override
testfunction), there’s more plumbing to do, but you have the advantage that doing things like calling into a “super”‘s version of a function can be quite straight-forward. The plumbing is sufficiently complex that I use a library for it, in my case my own library calledLineage, but Prototype has something similar calledClassand there are several others out there.When doing prototypical inheritance, you have constructor functions and then construct instances with them. The above might look something like this with
Lineage:Live example | source