8
\$\begingroup\$

I've implemented the following code which allows me to bolt modules of code on to my core library via the prototype chain. It's quite prescriptive so any user creating a module has to create an init method and also has to define a queue method:

(working fiddle: http://jsfiddle.net/wG9Pv/)

//Constructor
test = function() {
    this.tester = 'The instance was successfully created';
};

//A core method
test.prototype.amethod = function() {

};

//Extend method which facilitates the module system
test.extend = function(name,plugin) {
    test.prototype[name] = plugin.init;
    //later do something with the queue method that's been fed in via the 'plugin' object
};

//Add a module
test.extend('method1', { 

    init: function(val) {
        console.log(this.tester);
    },

    queue: function() {

    },

    render: function() {

    }    
});

//add another module
test.extend('method2',{ 

    init: function() {
        console.log('Init of the plugin has been fired');
    },

    draw : function() {}
});

var test = new test();
test.method1('boom!');
test.method2();

Now this all works well but is this a good way of achieving it?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Looks fine to me,

I would consider making extend a property of prototype though.

For nitpickings, I think

function Test() {
    this.tester = 'The instance was successfully created';
};

is preferred to

test = function() {
    this.tester = 'The instance was successfully created';
};

This ways developers will know to use new when using test. Please read Learning JavaScript Design Patterns for the cons of using the new keyword.

You probably want to store the entire plugin object provided to extend, not just keep init.

You probably want to throw an exception if the plugin does not have an init property.

I am not sure if you realize that method1 and method2 are at the end of the script also "core methods"?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.