Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is jQuery's $ a function and an object?

I mean object as in {} [object Object]. How does it do $(selector) and $.fn.init at the same time?

Can you give me a simple example please?

like image 418
David G Avatar asked Aug 28 '11 20:08

David G


People also ask

How is a function an object?

Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

Is jQuery an object or a function?

When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .

Is an object the same as a function?

An object is a collection of functions and data. A function is a collection of commands and data. When a bunch of functions work together to perform a certain task we may call this community of functionality an object.

Why JavaScript object is function?

In JavaScript, functions are called Function Objects because they are objects. Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.


2 Answers

This isn't unique to jQuery, but an aspect of javascript. All functions are objects. E.g.:

var f = function() { alert('yo'); } f.foo = "bar";  alert(f.foo); // alerts "bar" f();          // alerts "yo" 
like image 62
numbers1311407 Avatar answered Oct 11 '22 04:10

numbers1311407


Javascript is an object oriented language, so functions ARE objects, just fancy ones that you can call.

foo = function() { console.log("foo") } foo.bar = function() { console.log("bar") } foo() //=> prints "foo" foo.bar() //=> prints "bar" 
like image 32
Matt Briggs Avatar answered Oct 11 '22 05:10

Matt Briggs