...

View Full Version : Does anyone know a good tut on subfunctions?



Brett Bretterso
08-18-2005, 03:45 PM
I think they're called subfunctions. In some of my javascript research I ran across functions like this:


function AutoSuggestControl(oTextbox /*:HTMLInputElement*/,
oProvider /*:SuggestionProvider*/) {
blah blah blah

}

AutoSuggestControl.prototype.autosuggest = function (suggestions){

blah blah blah

}

I've successfully been able to modify the ones I've found, including adding more subfunctions, but when I've tried to create my own ones like this it wouldn't work. I'm not sure what I was doing wrong. Does anyone know a good tutorial that talks about these?

Brett Bretterson

martin_narg
08-18-2005, 04:56 PM
They are about creating new objects and extending object methods.

To create a custom object:


// generic book object
function Book(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

// create a new instance of Book called myBook
var myBook = new Book("Penguin Painting for Beginners", "martin_narg", 2002);

// reference an attribute of myBook
myBook.title; // returns "Penguin Painting for Beginners"

To create a method for an object:


Book.prototype.yearsSincePublished = function(d) {
var diff = d.getFullYear() - this.year;
return diff;
}

// so if I wanted to find how myBook has been published for, I could call the object's method like this:
var today = new Date();
myBook.yearsSincePublished(today); // returns 2 (because 2005 - 2003 = 2)

You can also extend current javascript objects, such as the number object. For instance I use this a lot:


Number.prototype.toDecimals = function(d) {
d = d || 2;
return Math.round(this*Math.pow(10, d))/Math.pow(10, d);
}

This is a Number object extension that enables you to generically round the number to a specified number of decimal places.
Usage:


var myPI = 3.14159;
myPI.toDecimals(1); // returns 3.1
myPI.toDecimals(); // returns 3.14 as if no decimal places supplied, it defaults to 2
(3.14159).toDecimals(3); // returns 3.142


By using these constructors to build and extend objects, it beomes very easy to see why JavaScript is an OO language - object oriented. Each object can be built and placed alongside each other to create bigger, quicker or more efficient applications.

Hope this helps!

m_n

Hope this information helps.

Brett Bretterso
08-18-2005, 05:22 PM
Thanks, I think that helps.

Brett Bretterson



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum