Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to Extend a JavaScript Library?

I am coming back to JavaScript after a long while working with Python, so I have forgotten some of the Javascript best practices.

I would like to work with predefined data structures such as the ones provided by bucket-js. However, I noticed that bucket-js does not provide much of a toString() method for its objects; so I would like to provide my own methods.

What would be the best way to extend library objects of this type such that the extensions are available throughout my project, but do not involve involve making changes to the library source code?

like image 331
Toaster Avatar asked Oct 19 '22 19:10

Toaster


1 Answers

Browser

If your target environment is browsers, then simply put the code that extends the library objects above the rest of your code.

Example:

<script src="bucket-js"></script>
<script>
        buckets.Set.prototype.toString = function() {
            //...
        }

        // Rest of your code
</script>

Node.js

If you are targeting Node.js, or browsers through something like Browserify that works with the same module-based organization, one method is to create your own patched module that patches the library object and then passes it back. You then require this module instead of the vanilla one.

More info: Monkey Patching in Node.js.

Example:

myPatchedBucketJS/index.js

var bucket = require('bucket-js');

buckets.Set.prototype.toString = function() {
    //...
}

module.exports = bucket;

main.js

var bucket = require('myPatchedBucketJS');
like image 66
lleaff Avatar answered Oct 21 '22 14:10

lleaff