Help with 'this' keyword in java script'

Discussion in 'JavaScript' started by minhazikram, Nov 11, 2011.

  1. #1
    Am new to JavaScript.

    Actually confused of 'this' keyword in javascript. If possible can anyone give me a brief idea about how to implement 'this' in the code.
     
    minhazikram, Nov 11, 2011 IP
  2. dixcoder

    dixcoder Member

    Messages:
    71
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    26
    #2
    this denotes current DOM object .

    for example

    function test(obj)
    {
    alert(obj.value);
    }

    <input type="text" id="testme" onblur="test(this)"/>
     
    dixcoder, Nov 12, 2011 IP
  3. md87

    md87 Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Even more, it doesn't have to be only DOM object. In general, it represents instance of any object. Usually, it is used in constructors for accessing attributes. You can look here: http://www.w3schools.com/js/js_objects.asp
     
    md87, Nov 16, 2011 IP
  4. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #4
    this can be as the html element that called the event (onclick,onmouseover,etc.)
    Example:
    <input type="submit" onclick="return validate(this);" />
    HTML:
    or

    this can be the object that contains a certain method/function.
    Example:
    
    var obj = new Object();
    obj.text = "The text";
    obj.getText = function(){
      return this.text;
    }
    
    Code (markup):
     
    JohnnySchultz, Nov 17, 2011 IP
  5. beven

    beven Well-Known Member

    Messages:
    483
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    113
    #5
    In some case we use "this" word for forum. for example when we have to change the class of any tag dynamically or at the time of event then we use this.form_name.field element. This refer to object which we are going to change values
     
    beven, Nov 17, 2011 IP