简体   繁体   English

扩展JavaScript库的最佳方法?

[英]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. 我在使用Python很长一段时间后回到JavaScript,所以我忘记了一些Javascript最佳实践。

I would like to work with predefined data structures such as the ones provided by bucket-js . 我想使用预定义的数据结构,例如bucket-js提供的数据结构。 However, I noticed that bucket-js does not provide much of a toString() method for its objects; 但是,我注意到bucket-js没有为其对象提供太多的toString()方法; 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? 扩展此类型的库对象的最佳方法是什么,以便扩展在整个项目中可用,但不涉及更改库源代码?

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 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. 如果您的目标是Node.js,或浏览器通过类似于基于模块的组织使用的Browserify ,那么一种方法是创建自己的修补模块,修补库对象然后将其传回。 You then require this module instead of the vanilla one. 然后,您需要此模块而不是香草模块。

More info: Monkey Patching in Node.js . 更多信息: 在Node.js中修补猴子

Example: 例:

myPatchedBucketJS/index.js myPatchedBucketJS / index.js

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

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

module.exports = bucket;

main.js main.js

var bucket = require('myPatchedBucketJS');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM