Creating a jQuery like “$” object

前端 未结 8 1379
伪装坚强ぢ
伪装坚强ぢ 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 04:18

    every time you call $ in jQuery it returns a new jQuery.init object. The jQuery.init object has functions that are then called.

    function test(type)
    {
      switch (type)
      {
        case 'azerty':
          return new type.a();
        case 'qwerty':
        default:
          return new type.b();
      }
    }
    
    test.a = function()
    {
      //a object defined
    };
    
    test.a.prototype.move = function()
    {
      //move function defined for the a object
    };
    
    etc...
    

    I just typed this on the fly, so it may need some tweaking

    This would allow you to call test('azerty').move();. More importantly: I hope you can see the general structure being used.

    Edit to add:

    To continue chaining functions like in jQuery, make sure you return the this object at the end of each function call:

    test.a.prototype.move = function()
    {
      //move function defined for the a object
      return this;
    };
    

提交回复
热议问题