2

I am building a really tiny library/framework as part of my journey to understand jQuery and how its core works.

I am wondering how jQuery selector elements are also returned as jQuery object and have all the methods of the jQuery. For example:

$('ul li').each(function(){ console.log($(this)); })

The $(this) is reference to the jQuery object for DOM element <li> and has all the methods of jQuery.

The log shows this:

[li, context: li, jquery: "2.1.0", constructor: function, selector: "", toArray: function…] 0: li context: li length: 1 __proto__: Object[0]

Here is a small part of the lib illustrating how I handle the initialisation and the each method.

(function( global, factory ) {factory( global );}
    (window, function( window ) {
        var document = window.document;
        var LibInit = function( selector ) {
            return new Lib( selector );
        };
        function Lib ( selector ) {
            this.selector = selector;
            return this;
        }
        Lib.prototype = {
            each: function(stack, callback) {
                var i;
                for ( i in stack ) {
                    if ( typeof stack[i] === 'object' )
                        callback(i, stack[i]);
                }
                return this;
            }
        }
        window.Lib = LibInit;
    }
));

Lib().each(document.querySelectorAll('ul li'), function(i,v){
    console.log(v);
})

This Lib each returns the direct DOM object for the specific element. How can I change it to return the DOM object wrapped with the object of Lib.

I am sorry for the complicated explanation, just can't think out a better way to explain it.

Also a side question. How console.log of $/jQuery returns string for the init function and $.plugin returns a method from the prototype. Basically there is no prototype of $ because the $ is reference to NOT instantiated function/object.

1
  • callback(i, $(stack[i]));?? Commented Feb 25, 2014 at 10:07

1 Answer 1

1
 for ( i in stack ) {
     if ( typeof stack[i] === 'object' )
         callback(i, new Lib(stack[i]));
     }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

How come I didn't think about this... Thanks! Also any idea about the side question? Or I should post it as separate question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.