我意识到在我当前的项目中使用jQuery有点过分,因为我最多只使用约10种方法,所以我决定使用jQuery的API样式创建一个更小的库。

该库的函数(称为Lib)返回3个属性:


  结果(包含查询结果)
  选择器(包含用于获取结果的选择器)
  长度(结果的长度)


库的功能如下所示:

function Lib(selector, context) {
  context = context || window.document;
  if(window === this) {
    return new Lib(selector, context);
  }
  this.results = map(context.querySelectorAll(selector));
  this.selector = selector;
  this.length = results.length;
  return this;
}


地图功能:

function map(collection) {
  var results = [];
  for(var i = 0; i < collection.length; i++) {
    results.push(collection[i]);
  }
  return results;
}


每次我从Lib.prototype中的方法访问“ this”对象时,都必须使用this.results修改元素this.selector以获取选择器,并通过this.length获取长度。

是否有可能同时污染元素和属性的“ this”对象。
例如:使用“ this”对象访问元素,
“ this.selector”属性可访问选择器,
“ this.length”访问元素的长度?

另外我该如何实施呢?

对于那些想知道这里的方法列表的人:

Lib("div").html("<div id=\"div-one\">Some Awesome HTML</div>")
Lib("div").text("Some Awesome Text")
Lib("div").attr("placeholder", "Search")
Lib("div").attr("placeholder")
Lib("div").css("background-color", "#fff")
Lib("div").css("background-color")
Lib("div").on("type", function(){/* do something when div has been clicked */})
Lib("div").off("type", function(){/* do something when div has been clicked */})
Lib("div").each(function(index, value){/* loop through each div and do something with them */})
Lib("input").blur(function(){/* do something when the focus has left input */})
Lib("input").focus(function(){/* do something when input has been focused on */})


注意:请不要担心对IE

最佳答案



var AP = []; //utility
function Lib(selector, context) {
    var me = Object.create(Lib.prototype, {
        selector: { configurable: true, value: selector },
        length: {writable: true, value: 0}
    });
    AP.push.apply(me, (context || document).querySelectorAll(selector));
    return me;
}

Lib.prototype.each = function(fn){
  for(var i=0, j=this.length; i<j; ++i)
    //if(false === fn(this[i], i, this)) break;
    fn(this[i], i, this);

  return this;
}

关于javascript - 是否有可能用元素和属性污染“this”对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35377429/

10-11 22:21
查看更多