Creating a jQuery like “$” object

前端 未结 8 1364
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 03:25

My end goal is being able to do something like this:

MyVar(parameter).functionToPerform();

Silly enough, even after reading up on how varia

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 03:57

    jQuery() is both a module with global methods, and a constructor. It automatically calls a constructor if it needs to. If we are not called with a new keyword, then this will not have been constructed with MyClass. We can detect that and call the function in constructor mode instead. Once we do that, then this will be an instance of MyClass and we can start adding stuff to it.

    var MyClass = function(context) {
        // if the function is called without being called as a constructor,
        // then call as a constructor for us.
        if (this.__proto__.constructor !== MyClass) {
            return new MyClass(context);
        }
    
        // Save the context
        this.context = context;
    
        // methods...
        this.print = function() {
            return "Printing";
        }
    
        this.move = function() {
            return this.context;
        }
    };
    
    $('#output').append('
  • print(): '+ MyClass().print() +'
  • '); $('#output').append('
  • move():'+ MyClass('azerty').move() +'
  • '); $('#output').append('
  • context: '+ MyClass('azerty').context +'
  • ');

    http://jsfiddle.net/rvvBr/1/

提交回复
热议问题