Search code examples
javascriptwebfunction-prototypes

what is the logic of this keyword in js inside method in method?


Could anyone tell "this" keyword in js .. I looked examples . There is a point that I can't understand.

   A.B=function()
    {
      this.x(5); // this refers to prototype of A.B
    }


   A.B.prototype= { 
    x:function(p)
    { this.a(p);  // this refers to prototype of A.B again  
                  // but I expect that this refers to protoype of x ???  

     }, 
        a:function(p){ return p;}
     }

Solution

  • If you call a method:

    a.b.c.d();
    

    then this is a.b.c inside of the method (everything except the final function name).

    If you call a constructor:

    var x = new Something();
    

    then this is a new fresh object inside of Something().

    Everywhere else this is the global object (which is the same as window in the browser).

    this is never a prototype. This can have a prototype.

    In your example:

    A.B = function() {
      this.x(5);
    }
    

    this is A (which doesn't have to be a prototype of A.B) if that method is called as A.B() - and is a new object if that method is called as new A.B().