3

I'm new in JavaScript and I want to understand something, for example in jQuery we have the jQuery object (often called $), but I'm confused here:

In jQuery when we want to select DOM nodes, we use jQuery selector, for example like this:

$('div');

But when we want to make a post to a server we call it like:

$.post({...});

My question is, how an object can behave like a function and an object at the same time? When I use $('div'), I'm calling a function and when I'm using $.post({...}) I'm accessing a function inside an object.

4
  • 1
    I suggest you to please review jquery.com it will help you a lot for more and enough learning Commented Nov 5, 2015 at 17:37
  • all simple: $ - not an object, this a function. Commented Nov 5, 2015 at 17:37
  • @Grundy no $ is an object and a function Commented Nov 5, 2015 at 17:41
  • @freedomn-m, $ is a function. this enough :-) Commented Nov 5, 2015 at 17:42

2 Answers 2

3

$( "h1" ).remove();

Most jQuery methods are called on jQuery objects as shown above; these methods are said to be part of the $.fn namespace, or the "jQuery prototype," and are best thought of as jQuery object methods.

However, there are several methods that do not act on a selection; these methods are said to be part of the jQuery namespace, and are best thought of as core jQuery methods.

This distinction can be incredibly confusing to new jQuery users. Here's what you need to remember:

1) Methods called on jQuery selections are in the $.fn namespace, and automatically receive and return the selection as this.

2) Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments, and their return value will vary.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm fine too, thank you for describing some JQuery internals for me :), can you show me how i can get this behavior in javascript, so how i can get a function/object in the same reference :)
@AbdessamedMansouri, just create function, and add property
@AbdessamedMansouri see my answer for how to do that
1

In summary: functions are objects.

function foo() {
    alert("bar");
}

foo.bar = "foobar";

alert(foo.bar);
foo();
alert(foo);

They're just special objects that you can add () to to call / run.

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.