Java-esque OOP in JavaScript and a jQuery fail

前端 未结 6 1736
走了就别回头了
走了就别回头了 2021-02-08 06:31

I\'m working on a project and I\'m really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford\'s JavaScript: The Good Parts and I\'m q

6条回答
  •  隐瞒了意图╮
    2021-02-08 07:12

    I would say the first way you're creating methods is a misuse of jQuery. The jQuery.fn.foo syntax is generally reserved for functions that act upon a DOM element but you're using them as static functions, by using an empty jQuery object.

    If you want to create static functions under the jQuery namespace, you can do:

    jQuery.foo = function(){};
    

    then call it via:

    jQuery.foo();
    

    instead of:

    jQuery.fn.foo = function(){};
    

    which allows you to do:

    jQuery('#someElementId').foo();
    

    In terms of OOP. there are many different approaches (module pattern, prototype, factory...). The way I generally approach it, is create a Class as a static function, then invoking it with the keyword new

    (function($){
        var undefined;
    
        $.ClassName = function(options){
            var self = this;
            var cfg = $.extend(true, {}, this.defaults, options);
    
            // ********************
            // start:private
            // ********************
            function _init(){
    
            };
    
            // ********************
            // start:public
            // ********************
            this.methodName = function(){
    
            };
    
            _init();
        };
    
        $.ClassName.prototype.defaults = {};
    })(jQuery);
    

    In terms of reusing functionality, there's a threshold after which decoupling is more detrimental than anything. Make sure you keep the right balance of modularity and organization.

提交回复
热议问题