jquery源码——jquery继承原型链上方法

jquery继承方法:

1、toArray 变数组

var arr = [];
jquery.prototype = {
    toArray: function() {
		return arr.slice.call( this );
	}
}

应用:

    console.log($('<div></div><div></div>').toArray());
    //  [div,div]

2、get 获取指定jquery元素

get: function (num) {
            if(num == null){
                return slice.call(this);
            }
            return num < 0 ? this[num + this.length] : this[num];
        }

应用:


    console.log($('<div>1</div><div>2</div>').get());
    // [div,div]
    console.log($('<div>1</div><div>2</div>').get(0));
    //  <div>1</div>

3、pushStack 入栈,先进后出;jquery内部使用较多(还没怎么弄懂有啥用……可能是记录上一层,end回退操作);

	pushStack: function( elems ) {

		// 合并
		var ret = jQuery.merge( this.constructor(), elems );

		// 标记prevObject
		ret.prevObject = this;

		// 返回值
		return ret;
	}

4、each、map、slice 用法;

5、first 选择第一位,last 选择最后一位,eq(num) 选择this[num];


        first: function () {
            return this.eq(0);
        },
        last: function () {
            return this.eq(-1);
        },
        eq: function (num) {
            var len = this.length;
            num = num >= 0 ? num : num + len;
            return this.pushStack(num >=0 && num < len ? [this[num]] : []);
        }

6、end 回退操作;

end: function() {
		return this.prevObject || this.constructor();
	}

猜你喜欢

转载自blog.csdn.net/weixin_41265663/article/details/82710221