tempcode
tempcode

Reputation: 175

How can jQuery seemingly be both an object and a method invoked by an object?

There's a workaround function for an API object called unsafeWindow for browsers that don't support it (via this person's github)

var unsafeWindow = (function() {
    var e1 = document.createElement('p')
    e1.setAttribute('onclick', 'return window;');
    return e1.onclick();
})();

// If the current document uses a JavaScript library, you can use it in
// your user script like this:
console.log(unsafeWindow.jQuery);

If unsafeWindow is an object (or in this case a function designed to mimic the object), how can it be used like $ = unsafeWindow.jQuery? I know this is how you map the function to the $ instead of the $ being a simple jQuery alias, but I'm just confused as to why, since I thought jQuery itself was an object, and is being invoked here like one would a method.

Edit: Thank you for your answers, I wish I could "check mark" all of you, thanks for the help!

Upvotes: 0

Views: 86

Answers (4)

Xotic750
Xotic750

Reputation: 23482

Jquery is a constructor function with methods attached. When used as $.each(), you are just calling the method each() that is attached to the function (object). When you use $(), it calls an internal new jQuery() and returns it, giving you access to it's prototype methods.

Upvotes: 1

Thanh Trung
Thanh Trung

Reputation: 3804

Don't let the . blindfold you. object.something is getting the property something which could be anything (function, variable, object, value..), while object.something() is applying the method something

Upvotes: 2

Andbdrew
Andbdrew

Reputation: 11895

In javascript, functions are objects!

Upvotes: 5

shishirmk
shishirmk

Reputation: 425

When you do $ = unsafeWindow.jQuery you are assigning the jQuery object to $ like you rightly pointed out. You are not invoking any function. Invoking a function in javascript involves adding a parenthesis () at the end.

Upvotes: 1

Related Questions