Jump to content

Quick Question...


RobberBaron

Recommended Posts

In jQuery, since the dollar references a function that creates a new jQuery object:

$ = function(a,b){return new jQuery.fn.init(a,b); //something like that};

Then how come it can be used as a table:

$.post({blah});

Basically, I would like the ability to recreate this, for I am making a JavaScript library and the $ also creates a new library object.

Link to comment
Share on other sites

You don't read about this a lot in tutorials, but like every other data structure in JavaScript, a function is an object. This means that it can be assigned properties and even additional methods simply by using dot notation. Here's a trivial example

$ = function() {   alert("Hello");}$.bob = 2;$.add = function (x) {   alert(this.bob + x);};alert ($.add(2) );

Link to comment
Share on other sites

You don't read about this a lot in tutorials, but like every other data structure in JavaScript, a function is an object. This means that it can be assigned properties and even additional methods simply by using dot notation.
...and that is what I absolutely love about JavaScript. Creating, manipulating, and passing objects is so easy, especially with the help of JSON.
Link to comment
Share on other sites

Thanks. So if in the function I assign values, I can call them from the function object. Just what I needed :)EDIT: Hold on, I'm getting a problem. Would this not work (example):

$ = function() {   alert("Hello");   this.bob = 2;}$.add = function (x) {   alert(this.bob + x);};alert ($.add(2) );

Link to comment
Share on other sites

Negative. It's a matter of scope. this always refers to a property's parent. The $ function/method is technically a property/child of the window object. Calling $() and window.$() are equivalent, so this refers to window, and window.bob is undefined. The add method is a property of $, so this refers to $.

Link to comment
Share on other sites

I should have mentioned that there is a way to do what you want. Consider:

$ = function() {   alert(arguments.callee.bob); // this is the trick};$.bob = 2;$.add = function (x) {   return this.bob + x;};$(); // alerts 2alert ($.add(2) ); // alerts 4

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...