Javascript类返回数组,创建类似jQuery的库 [英] Javascript Class return array, create library like jQuery

查看:91
本文介绍了Javascript类返回数组,创建类似jQuery的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating javascript library like jQuery, I have successfully adding prototype html() but if I call it with $(selector) it return object like {'el' : [array]} and if change in function to return this.el; it return array but I can't call .html().

如何在不破坏原型的情况下返回[array]?

How it can return [array] instead without breaking prototype?

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])

<div id="test">AAAAAAA</div>

推荐答案

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

finally it solved by looking Zepto source code, the magic to convert object to array is you have to create $.prototype.splice, it copied from the Array.splice

// 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>

这篇关于Javascript类返回数组,创建类似jQuery的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆