35行的山寨版jQuery

jQuery对象本质上是一种类数组对象
var $$ = function (nodeList) {

    return new $$.fn.init(nodeList);
};

$$.fn = $$.prototype = {

    toString: function () {
        return this.slice();
    },
    constructor: $$,
    init: function ( arr ) {    // 创建类数组对象
        for (var i = 0, l = arr.length; i<l; i++) {
            this[i] = arr[i];
        }

        this.length = arr.length;
    },
    each: function (fn) {
        for(var i = 0, l = this.length; i<l; i++){
            fn.call(this[i], i);
        }
    },
    eq: function (i) {
        return i === -1 ? this.slice(i) : this.slice(i, i + 1);
    },
    slice: function (a, b) {
        start = a || 0;
        end = b || self.length;
        return Array.prototype.slice.apply( this, [start, end] );
    }
    
    // ... ...
};

$$.fn.init.prototype = $$.fn;

使用示例:

var para = $$( document.getElementsByTagName('p') );

para.each(function(){

    this.className += " " + 'goodbye'; 

});

 

原文地址:https://www.cnblogs.com/MyNameIsJim/p/3519374.html