Javascript类返回数组,创建类似jQuery的库

时间:2019-02-03 17:49:27

标签: javascript jquery html

我正在创建类似jQuery的JavaScript库,我已经成功添加了原型html(),但是如果我用$(selector)调用它,它将返回对象{'el' : [array]},并且如果函数更改为{{ 1}}返回数组,但我不能调用return this.el;

如何在不破坏原型的情况下返回.html()

[array]
window.$ = function(selector) {
  if (!(this instanceof $)) {
    return new $(selector);
  }
  this.el = [];
  this.html = function(str) {
    this.el.forEach(function(el) {
      el.innerHTML = str;
    });
  };

  (function(self) {
    for (var eList = document.querySelectorAll(selector), i = eList.length - 1; i > -1; i--) {
      self.el[i] = eList[i];
    }
  })(this);
 
  return this;
};

$('#test').html('BBBBB')
console.log($('#test')[0])

2 个答案:

答案 0 :(得分:1)

 window.$ = function(selector) {
      var x = [];
      x = document.querySelectorAll(selector);
      console.log(x);
      return x;
    };
NodeList.prototype.html = function(str) {
	console.log(this);
	this.forEach(function(el){
    	el.innerHTML = str;
    });
}


console.log($('#test').html('BBBBB'))
<div id="test"></div>

我在NodeList数组中扩展了html方法。告诉我是否适合您。

答案 1 :(得分:1)

最后,它通过查看Zepto源代码得以解决,将对象转换为数组的神奇之处在于您必须创建$.prototype.splice,它是从Array.splice复制来的

class return array

// only load if no jQuery on the page
if (window.$ === undefined) window.$ = (function () {
    var $, zepto = {}, emptyArray = [];

    function Z(dom, selector) {
        var i, len = dom ? dom.length : 0;
        for (i = 0; i < len; i++) this[i] = dom[i];
        this.length = len;
        this.selector = selector || '';
    }
    Z.prototype = {
        splice: emptyArray.splice,
        forEach: emptyArray.forEach,
        html: function (str) {
            this.forEach(function (el) {
                el.innerHTML = str;
            });
        }
    };
    zepto.Z = function (dom, selector) {return new Z(dom, selector);};
    zepto.init = function (selector, context) {
        if (!selector) return zepto.Z();
        var dom = document.querySelectorAll(selector);
        return zepto.Z(dom, selector);
    };
    $ = function (sel, ctx) {return zepto.init(sel, ctx); };

    return $;
})();

$('.test').html('DDDDD');
console.log($('.test'));
<div class="test"> AAAA </div>
<div class="test"> BBBB </div>
<div class="test"> CCCC </div>