Best practices for JQuery namespaces + general purpose utility functions

前端 未结 2 646
南旧
南旧 2021-01-31 23:26

What are some current \"rules of thumb\" for implementing JQuery namespaces to host general purpose utility functions?

I have a number

2条回答
  •  太阳男子
    2021-02-01 00:27

    For jQuery plugins and such the pattern is to use $.fn.myPlugin if you want it to be available on elements, and $.whatever if you just want to use the namespace. I recommend reading the official Plugins Authoring document and these articles.

    But jQuery aside, the easiest way to namespace your utils would be along these lines:

    var utils = window.utils || {};
    utils.method = function(){};
    

    The basics of namespacing in JS hasn't really changed lately - You should check out snook's article, DED's elegant approach and this SO question.

    The main advantage of using a self-invoked function to declare namespaces is you can execute stuff privately before returning the object. Also, the object will be ready for auto-complete by your console, which you'll miss on the $ namespace because jQuery returns a function rather than an object.

提交回复
热议问题