javascript - 关于jq的两个问题
PHP中文网
PHP中文网 2017-04-10 14:32:08
0
2
461

1.在jq源码里经常会有this.constructor(param)语句,比如this.constructor(context).find(),这里的作用是什么?constructor不是原型对象里的一个属性,指向构造函数么?求解答

2.eq的源码是这样写的:
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
这样不是将当前找到的元素和之前的jq对象合并么?那么这样的话length应该是原来length+1,但是为什么是?length = 1?

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
阿神
  1. 是啊,this.constructor === jQuery,有什么不妥么?this是函数内部自有的,jQuery是函数外部作用域的变量,你说用哪个好呢?

  2. 去看看pushStack,它和push不是一个意思,这个是某个版本的pushStack源码:

    // Take an array of elements and push it onto the stack
    // (returning the new matched element set)
    pushStack: function( elems, name, selector ) {
    
        // Build a new jQuery matched element set
        var ret = jQuery.merge( this.constructor(), elems );
    
        // Add the old object onto the stack (as a reference)
        ret.prevObject = this;
    
        ret.context = this.context;
    
        if ( name === "find" ) {
            ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
        } else if ( name ) {
            ret.selector = this.selector + "." + name + "(" + selector + ")";
        }
    
        // Return the newly-formed element set
        return ret;
    }
    
伊谢尔伦

pushStack 的目的貌似是为了end()的时候找到最初的那个对象。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template