3

我的目标是仅使用 Javascript 从头开始​​复制普通的 jQuery 每种类型的函数。到目前为止,这是我的代码:

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

如您所见,每个都显示为错误。我应该如何解决这个问题?

4

2 回答 2

4

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

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 本身也使用它)并且在很多情况下都能很好地为您服务。

于 2013-07-06T14:10:50.583 回答
1

像这样的东西……???

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;
}
于 2013-07-06T13:54:45.753 回答