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 に答える