尝试从头开始使用Javascript创建each()类型的jQuery函数



我的目标是只使用Javascript从头开始复制普通的jQuery-each类型函数。这是我到目前为止的代码:

// Created a jQuery like object reference
function $(object) {
    return document.querySelectorAll(object);
    this.each = function() {
        for (var j = 0; j < object.length; j++) {
            return object[j];
        }
    }
}
console.log($('.dd')); // returns NodeList[li.dd, li.dd]
$('.opened').each(function() {
    console.log(this);
}); // Results in an error [TypeError: $(...).each is not a function]

正如您所看到的,每个都显示为一个错误。我该怎么着手解决这个问题?

像这样工作的轻量级类是:

function $(selector) { 
    // This function is a constructor, i.e. mean to be called like x = new $(...)
    // We use the standard "forgot constructor" trick to provide the same
    // results even if it's called without "new"
    if (!(this instanceof $)) return new $(selector);
    // Assign some public properties on the object
    this.selector = selector;
    this.nodes = document.querySelectorAll(selector);
}
// Provide an .each function on the object's prototype (helps a lot if you are
// going to be creating lots of these objects).
$.prototype.each = function(callback) {
    for(var i = 0; i < this.nodes.length; ++i) {
        callback.call(this.nodes[i], i);
    }
    return this; // to allow chaining like jQuery does
}
// You can also define any other helper methods you want on $.prototype

你可以这样使用它:

$("div").each(function(index) { console.log(this); });

我在这里使用的模式是众所周知的(事实上jQuery本身也使用它),在很多情况下都会很好地为您服务。

类似这样的东西。。。??

function $(object) {
    var obj = {
        arr : document.querySelectorAll(object),
        each : function(fun){
            for (var i = 0; i < this.arr.length; i++) {
                fun.call(this, this.arr[i]);
            }
        }
    }
    return obj;
}

最新更新