Functions are the building blocks of Javascript. A function is a collection of statements that can be run anywhere at anytime. Functions are declared with the keyword, you guessed it, function, followed by a set of arguments, and finally by the code to execute enclosed in braces.
function
Unfortunately unlike C++, Java, and C# you can not overload Javascript functions. I assume this is because Javascript is not a strongly typed language and therefore it doesn't really make sense to overload a function. If you do try to overload a function the very last definition of that function will "win" when called simply because it overrides any function (with the same name) before it.
When I started writing Javascript I knew of only one way to define a function:
function functionName (arg0, arg1, ...., argN) { statements }
Since Javascript functions are actually variables (which is really really cool and powerful) you can define and redefine functions as local variables, this is the other way you can define a function:
var myFunc; if (Math.random() < 0.5) { myFunc = function() { alert('heads'); }; } else { myFunc = function() { alert('tails'); }; } myFunc(); // alerts "heads" or "tails" depending on random value
You can also pass functions as parameters to other functions, which is very useful for callback functions:
function do_something(callback_function) { alert('hello'); if (callback_function) { callback_function(); } } var my_callback = function() { alert('goodbye'); }; do_something(my_callback); // alerts "hello" and then "goodbye"
You can also return a function from a function:
function get_multiplier(factor) { return function(num) { return num * factor; }; } var times_5 = get_multiplier(5); var result = times_5(10); alert(result); // alerts "50" var six_times_two = get_multiplier(6)(2); alert(six_times_two); // alerts "12"
You can also define "anonymous" functions without a name and even execute them:
(function(first_name, get_last_name) { var last_name = get_last_name(); alert(first_name + ' ' + last_name); // alerts "Jesse Skinner"; })('Jesse', function(){ return 'Skinner'; });
Note that in order to execute an anonymous function you have to wrap it in () parentheses first. Taken from www.thefutureoftheweb.com
()
I've been writing some heavy lifting JavaScript lately and found something interesting I thought I might share with you. There are a couple of ways to implement inheritance in JavaScript but since that is outside the scope of this post I'll stick to the prototype chaining paradigm (which, according to Nicholas Zakas is the form of inheritance actually intended use in ECMAScript).
Consider the following code:
function Disposable() { alert("Disposable constructor"); }; Disposable.prototype.dispose = function () { alert("In base clase dispose"); }; function MemoryHog() { alert("MemoryHog constructor"); // Call super class' constructor Disposable.call(this); }; // Inherit Disposable MemoryHog.prototype = new Disposable(); // override MemoryHog.prototype.dispose = function () { alert("Deleting MemoryHog resources...."); }; var recursiveClass = new MemoryHog(); recursiveClass.dispose();
What do you expect the output to be?
The output is, well a little different than what you would expect from a very similar Java or C# exercise:
Disposable constructor MemoryHog constructor Disposable constructor Deleting MemoryHog resources....
What I found interesting is that the Disposable constructor gets called when the page loads. The second time the Disposable constructor gets called is not when an instance of MemoryHog is instantiated (not in the automatic/OOP way it would happen) but when MemoryHog's constructor calls it's super classes constructor.
Disposable
MemoryHog
In any event while developing JavaScript classes I highly recommend you use some sort of JavaScript linter. The best (public) one out there is probably JSLint.com brought to you by non other than Yahoo! JavaScript chief, Douglas Crockford. Additionally I found it very useful to use JSUnit to write unit tests for my JavaScript... yeah, you heard me, unit tests for your JavaScript. It helped me refactor easily knowing that I could always run my tests (I use the built in Test Suite Runner) and know that I didn't break anything.
This is kind of a javascript puzzler that I can't take personal credit for but I thought it was quite interesting.
What do the following evaluate to in Javascript: null < 0 null == 0 null <= 0
null < 0 null == 0 null <= 0
Think about it for a second before scrolling down to the answers. No really, try to solve it first.
while you wait for it... (Sia - The Girl You Lost To Cocaine)
null < 0 --> false null == 0 --> false null <= 0 --> true
If you got the correct answers and you know why they are correct you can stop reading now and give yourself a pat on the shoulder. I didn't get the last one correct and I wasn't sure why...
It turns out that "<" is the fundamental relationship operator in javascript. That basically means that hybrid relationship operators are translated by the interpreter to a "<" operation with the addition of other fundamental operators like !. So how does this make null <= 0 you ask? x <=y is calculated as !(y < x) and since 0 < null still evaluates to false negating that result returns true.
!
null <= 0
0 < null
false
true
There was an interesting discussion in one of the mailing lists here at work regarding the use of local vs. global variables and how fast they were in comparison. **It turns out that accessing variables in a more local scope is indeed faster based on some easy measuring (local vs. global access). The discussion started when something like this was introduced:
Consider Class "MyClass" that has two member variables:
function MyClass() { this.foo_ = 'joe'; this.elem_ = document.getElementById('bar'); ... };
Now consider the usage of such a class, which would be more efficient (for multiple accesses of the same member), this:
MyClass.prototype.updateSomething = function() { if (this.foo_) { this.elem_.innerHTML = this.foo_; } else { this.elem_.innerHTML = 'somethingElse'; } };
OR
MyClass.prototype.updateSomething = function() { var foo = this.foo_; var elem = this.elem_; if (foo) { elem.innerHTML = foo; } else { elem.innerHTML = 'somethingElse'; } };
OK, so accessing variables in a more local scope is faster than accessing variables using this, but it gets interesting when you introduce a large number of properties (imagine MyClass has 1000 properties appended to it), the local access stays almost identical in speed compared to the case where MyClass only had 2 properties where the this based access grows relative to the number of properties it has to search through. The speed differs in single digit seconds but a difference of 4-9 seconds per access could accumulate in cases where you have many references to such properties.
this
While looking at the tests people set up I noticed an attribute on the <script> tag that I had never noticed before, the attribute defer="defer" defers execution of your JavaScripts to speed initial content display.. That's pretty cool, first time I ever ran into this. The "history" of this attribute, as mentioned here:
defer="defer"
First introduced by Internet Explorer 4, the defer attribute of the script element is now part of the HTML 4 and XHTML specifications. The defer attribute gives a hint to the browser that the script does not create any content so the browser can optionally defer interpreting the script. This can improve performance by delaying execution of scripts until after the body content is parsed and rendered. Here's the brief paragraph describing the defer attribute from the HTML 4.01 specification: When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering. I'm about to make a big switch in my technical career. As of Monday (I think) I'm diving deep into the Linux - Java - GWT world and leaving my old pall .net behind... it's going to be challenging but rewarding. Post View spanish french italian german 3/12/2008 8:26:12 PM Redundant Pointers to Functions and the Prototype Paradigm The other day a coworker asked me if I knew what the difference between the following two Car objects is: function Car(make, model, price) { this.make = make; this.model = model; this.price = price; this.showMake = function() { alert(this.make); }; } And function Car(make, model, price) { this.make = make; this.model = model; this.price = price; } Car.prototype.showMake = function() { alert(this.make); }; Initially I jumped to the conclusion that there really doesn't seem to be much of a difference. The first constructor simply creates a pointer to the showMake function using this and the second does the same thing using the prototype paradigm. As far as I knew the end result was identical. Furthermore I was quite sure that the prototype property was "meant" to be used for existing objects in Javascript to enable developers to extend/tailor them. For example, if you wanted to create a Queue in Javascript you could extend the Array object by adding two new methods: Array.prototype.enqueue = function(o) { this.push(o); } Array.prototype.dequeue = function() { return this.shift(); } Turns out I was partially correct. The outcome, from the consumers point of view, of the two Car constructors would be identical. You basically defined the same object. Additionally the prototype property is used to extend/modify objects. The only thing I didn't know was that by creating a pointer from this to the showMake function in the first example Javascript would create an instance of the showMake function with every call to new Car(..) and essentially "waste" memory. The second way (aka the "prototype paradigm") creates a pointer to the same instance of the showMake function belonging to the Car object. Semantically, everything looks like it belongs to Car but you are using up less memory. Post View spanish french italian german 2/2/2008 11:55:53 AM Javascript Cookies My good buddy Jon (aka JonK) suggested I cookie the comment data... which makes sense and has been on my backlog for a while now. Since I've been in "coding mode" since I finally got tests (that I've been working on all week) to pass yesterday I figured I should. So I did. The article is simply to show off the cookie functions I stole borrowed from PPK // Create a cookie with the a name, value and optional expiry // param @name - the name of the cookie // param @value - the value to store in it // param @days (optional) - how many days to store this cookie function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } // Read a cookie by name // param @name - the name of the cookie to search for function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } // Erase/remove cookie by name // param @name - the name of the cookie to remove function eraseCookie(name) { createCookie(name,"",-1); } I found this very easy to use, I hope you do to. Post View spanish french italian german 12/22/2007 4:49:31 PM Top Ten Javascript Functions of All Time Since I find myself searching for this article all the time, and since I have mysteriously neglected my Javascript category, I thought it would be best if I blogged about it. There is actually a podcast about this article which can be found here. Top 10 custom JavaScript functions of all time If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today. Prototype's famous $ function: function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } And while I'm at it, I would like to plug my favorite Javascript book that will, in my buddies Chirs' words, turn you into a black belt Javascript Ninja!! Post View Post Your Comment Name: Url: Send Thanks for contacting me. I will get back to you as soon as I can. close Name: Email: Send
First introduced by Internet Explorer 4, the defer attribute of the script element is now part of the HTML 4 and XHTML specifications. The defer attribute gives a hint to the browser that the script does not create any content so the browser can optionally defer interpreting the script. This can improve performance by delaying execution of scripts until after the body content is parsed and rendered.
Here's the brief paragraph describing the defer attribute from the HTML 4.01 specification:
I'm about to make a big switch in my technical career. As of Monday (I think) I'm diving deep into the Linux - Java - GWT world and leaving my old pall .net behind... it's going to be challenging but rewarding.
The other day a coworker asked me if I knew what the difference between the following two Car objects is:
function Car(make, model, price) { this.make = make; this.model = model; this.price = price; this.showMake = function() { alert(this.make); }; }
And
function Car(make, model, price) { this.make = make; this.model = model; this.price = price; } Car.prototype.showMake = function() { alert(this.make); };
Initially I jumped to the conclusion that there really doesn't seem to be much of a difference. The first constructor simply creates a pointer to the showMake function using this and the second does the same thing using the prototype paradigm. As far as I knew the end result was identical. Furthermore I was quite sure that the prototype property was "meant" to be used for existing objects in Javascript to enable developers to extend/tailor them. For example, if you wanted to create a Queue in Javascript you could extend the Array object by adding two new methods:
showMake
prototype
Queue
Array
Array.prototype.enqueue = function(o) { this.push(o); } Array.prototype.dequeue = function() { return this.shift(); }
Turns out I was partially correct. The outcome, from the consumers point of view, of the two Car constructors would be identical. You basically defined the same object. Additionally the prototype property is used to extend/modify objects. The only thing I didn't know was that by creating a pointer from this to the showMake function in the first example Javascript would create an instance of the showMake function with every call to new Car(..) and essentially "waste" memory. The second way (aka the "prototype paradigm") creates a pointer to the same instance of the showMake function belonging to the Car object. Semantically, everything looks like it belongs to Car but you are using up less memory.
My good buddy Jon (aka JonK) suggested I cookie the comment data... which makes sense and has been on my backlog for a while now. Since I've been in "coding mode" since I finally got tests (that I've been working on all week) to pass yesterday I figured I should. So I did.
The article is simply to show off the cookie functions I stole borrowed from PPK
// Create a cookie with the a name, value and optional expiry // param @name - the name of the cookie // param @value - the value to store in it // param @days (optional) - how many days to store this cookie function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } // Read a cookie by name // param @name - the name of the cookie to search for function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } // Erase/remove cookie by name // param @name - the name of the cookie to remove function eraseCookie(name) { createCookie(name,"",-1); }
I found this very easy to use, I hope you do to.
Since I find myself searching for this article all the time, and since I have mysteriously neglected my Javascript category, I thought it would be best if I blogged about it. There is actually a podcast about this article which can be found here.
Top 10 custom JavaScript functions of all time
If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today. Prototype's famous $ function: function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; }
If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today.
Prototype's famous $ function:
function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; }
And while I'm at it, I would like to plug my favorite Javascript book that will, in my buddies Chirs' words, turn you into a black belt Javascript Ninja!!
close