Why is it possible to query jQuery('div') like an array?

后端 未结 5 1343
礼貌的吻别
礼貌的吻别 2021-01-05 01:59

I got another question regarding jQuery\'s architecture. $(\'div\') constructs a new jQuery object:

$(\'div\') instanceof jQuery; /         


        
5条回答
  •  [愿得一人]
    2021-01-05 02:44

    Treating a jQuery object like an array is an application of duck typing. From Wikipedia:

    In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

    In other words, it's not important that the jQuery function actually return an array instance, as long as it provides the necessary properties (e.g. length, numeric indices) and methods to act like an array.

    JavaScript has other array-like objects. For example, the arguments object isn't an array, either, but it has properties (like length) that allow you to pretend it is.

提交回复
热议问题