13

I've been wondering for a long time how jQuery can be both a function and an object property.

You can use it like a function, jQuery(...) and you can use it like a property jQuery.ajax(...)

How can you achieve a such thing in Javascript?

3 Answers 3

15

functions are objects in javascript. So you can have your main function

var $ = function() {  alert('wat'); }

and then extend it

$.fadeTo = function() { alert('fadeto'); }
Sign up to request clarification or add additional context in comments.

2 Comments

mhm, I see... A Javascript class doesn't not have the notion of static/dynamic methods?
@SBSTP: JavaScript doesn't have classes at all, it's a prototypical language, not a class-based one. It has constructor functions. Constructor functions create objects.
9

Because in JavaScript, functions are objects that can have properties:

function test() { ... }

test.a = function () { ... };
test.a(); // totally valid

1 Comment

Ah, I didn't realize this. Question: In your example, can test.a be defined within the initial function test() {...} declaration, or must test.a be declared separately in order to be accessible outside of test()? In other words, is it possible to define the a property from within the test(){...} declaration such that it is still accessible from outside of test()? I cannot seem to find the answer anywhere else.
2

I think the concept of what exactly is jQuery in terms of code concepts is quite confusing. I ran across this link, which explains the jQuery Architecture in a very simple and easy manner : http://blog.mikecouturier.com/2010/02/beginning-with-jquery-solid-foundation_22.html

So, in short, $ is an alias for a JavaScript function called 'jQuery', and methods invoked by using a dot notation like $.trim ( ) are static methods on the 'JavaScript 'jQuery' function. Note that a function inherits from object in JavaScript, and so a function is an object in JavaScript.

Comments

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.