2017-04-27 99 views
6

我试图创建一个可以支持方法链接的迷你jQuery克隆。到目前为止,我想出了这样一段代码:jQuery对象数据结构

var $ = (function() { 

    var elements = []; 

    function methodOne() { 
    console.log('Method 1'); 
    return this; 
    } 

    function methodTwo() { 
    console.log('Method 2'); 
    return this; 
    } 

    return { 
    methodOne: methodOne, 
    methodTwo: methodTwo 
    }; 
}()); 

在网页加载时,$变量被由IIFE返回jQuery的克隆对象的填充。

我的问题是,我怎样才能使$对象作为一个函数直接调用,同时仍然保持方法链接功能?

现在,我可以使用$.methodOne().methodTwo(),但我不能像使用jQuery一样使用$('some parameter').methodOne().methodTwo()

+0

我还没有尝试过,但我认为你可以使用'class' javascript和'extends' Jquery!我认为这样做。你知道,我很好奇,我也会尝试。 – funcoding

回答

3

var $ = function (param) { 
 

 
    var elements = []; 
 
    console.log(param); 
 

 
    function methodOne() { 
 
    console.log('Method 1'); 
 
    return this; 
 
    } 
 

 
    function methodTwo() { 
 
    console.log('Method 2'); 
 
    return this; 
 
    } 
 

 
    return { 
 
    methodOne: methodOne, 
 
    methodTwo: methodTwo 
 
    }; 
 
}; 
 

 
$('This is a param').methodOne().methodTwo();

1

Working fiddle。评论应该或多或少地自我解释。

它可能看起来有点长,但它可以让你每次调用它时创建新的迷你jQuery对象。

var _ = (function() { 

    var Magic = function(query){ 
     if(window === this) 
      return new Magic(query); 

     // reference to itself 
     var that = this; 

     //assign pseudo public methods and variables 
     that.elements = []; 
     that.methodTwo = methodTwo; 
     that.methodOne = methodOne; 

     //fills inner element array with DOM element 
     _get(query); 

     function _get(query){ 
      var elem = document.getElementById(query); 
      that.elements.push(elem); 
     } 

     function methodOne() { 
      console.log('Method 1'); 
      return that; 
     } 

     function methodTwo() { 
      console.log('Method 2', that.elements); 
      return that; 
     } 

     return this; 
    } 

    //returns function, which is assigned to a "_" variable 
    return function(query){ 
     //everytime "_" is called, it will return new instance for object Magic which makes all the work 
     return new Magic(query); 
    } 

}());