How is $('h1') logging to the web console as an array in jQuery?

后端 未结 1 1016
情深已故
情深已故 2020-12-29 10:48

If you do console.log($(\'some selector\')) in the browser, it returns what looks like an array (first line):

相关标签:
1条回答
  • 2020-12-29 11:20

    You make your object inherit Array using the prototype, like so:

    function SomeType() {
        this.push(16);
    }
    
    SomeType.prototype = [];
    SomeType.prototype.constructor = SomeType; // Make sure there are no unexpected results
    
    console.log(new SomeType()); // Displays in console as [16]
    

    And, of course, all jQuery objects are instances of the jQuery function/constructor, so that's how jQuery does it. As a bonus, because of the inheritance, you get all the methods from Array, and the indexing that comes with it too!

    0 讨论(0)
提交回复
热议问题