PDA

View Full Version : prototypes?


scriptkeeper
06-25-2003, 04:20 AM
This function is very interesting and I would like to find out more about how it works? I understand pretty much the whole function but the hilited part below and what exactly it is doing? Could some one clear the smoke?


String.prototype.deleteCharAt = function( index )
{
return this.substring( 0, --index ) + this.substring( ++index );
}
var mystring = "abcde";
alert( mystring.deleteCharAt( 3 ) );

Terry
06-25-2003, 04:43 AM
Hi,

The prototype property is how Object Oriented programming works in javascript. The function that you posted made a new method that will work on any String object. You can extend objects to have properties or functions. The example you posted will work like this:

var myStr = new String("hey there");

alert(myStr.deleteCharAt(4)); // returns "hey here"

You can extend any object with the prototype property... Arrays, numbers, Strings etc. Your only limited by your imagination.

some reference:
http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm

http://www.sitepoint.com/print/470

http://www.sitepoint.com/print/473

http://www.webdevelopersjournal.com/articles/jsintro3/js_begin3.html

http://www.crockford.com/javascript/private.html


- Terry

beetle
06-25-2003, 05:02 AM
That looks like my work :D

There are several built-in objects in javascript (also called host objects or static objects). Off the top of my head, these are

String
Number
Object
Function
Math
Date
RegExp

I might be missing one or two. Read the articles Terry posted, you'll learn some good stuff

ahosang
06-25-2003, 01:08 PM
Yes, and in the all-powerful Mozilla (Netscape 6+), you can prototype HTMLElements, the Document, or any object(except the window objects - location etc)
Too bad you can't for the one that most people use - IE