Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: This.HELP

  1. #1
    Regular Coder syco__'s Avatar
    Join Date
    Oct 2005
    Location
    Australia
    Posts
    194
    Thanks
    41
    Thanked 4 Times in 4 Posts

    This.HELP

    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.

    Code:
    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));
    Thanks.
    .pLeAd InSaNiTy.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    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
    Code:
    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.

  • #3
    Regular Coder syco__'s Avatar
    Join Date
    Oct 2005
    Location
    Australia
    Posts
    194
    Thanks
    41
    Thanked 4 Times in 4 Posts
    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
    .pLeAd InSaNiTy.

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •