jQuery对象数据结构

时间:2017-04-27 10:50:10

标签: javascript 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()

2 个答案:

答案 0 :(得分: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 :(得分: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);
    } 

}());