View Full Version : This.HELP

07-14-2011, 03:50 PM
I have been working on exercises in a same teach yourself JavaScript as of late and have come across this code to add a method to an existing Object and but getting confused with the lines in bold can someone just tell me what it actually is i have totally confused myself.

function addhead (level) {
html = "H" + level
text = this.toString()
start = "<" + html + ">";
stop = "</" + html + ">";
return start + text + stop

String.prototype.heading = addhead
document.write ("This is heading 1" .heading(1));
document.write ("This is heading 2" .heading(2));
document.write ("This is heading 3" .heading(3));


07-15-2011, 09:59 AM
The second one is the main one. It adds the method heading to the String prototype. Essentially this will add the method .heading to all string objects. The definition of this method is in addhead(). Inside of this function the object "this" refers to the current string object.

So if you do something like this

var newString = "This is a test".heading(4);

you will get "<H4>This is a test</H4>" as newString. So essentially this method wraps a string into an HTML heading.

07-17-2011, 04:24 AM
String.prototype.heading = addhead

so this line says add .heading to the String object and the actually word heading could be anything?? i think thats where i am getting confused cause heading sounds like it was an already existing method

07-17-2011, 09:46 AM
Right. String.prototype.heading will (re)define the method .heading for the String.prototype. That means: If it doesn't exist yet, it will be created, otherwise it will be overwritten.