Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How "this" keyword works in Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 364
    Comment on it

    The code example of this keyword in Javascript

      var fullname = 'David';
        var obj = {
           fullname: 'john mars',
           prop: {
              fullname: 'Brett',
              getFullname: function() {
                 return this.fullname;
              }
           }
        };
    
        console.log(obj.prop.getFullname());
    
        var testing = obj.prop.getFullname;
    
        console.log(test());
    

    The example code written above will print Brett and David. The reason behind this is that the context of a function defined above (context refers to the global object). In JavaScript , it depends on how a function is invoked.

    In the above code- console.log() call, getFullname() is defined as the function of the ( obj.prop ) object. So, the function defined above will returns the fullname property of this object.

    getFullname() is assigned to the testing variable so context refers to the global object .

    For this reason, the function returns the value of a property called fullname of window.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: