0
function Parent(){ 
this.name = "parent";
console.log("this gets executed");
}
function Child(){
 Parent.call(this) // doesnt the this here belongs to the child object?
}
var o = new Child();

Why does the this inside the child object invokes the parent constructor? Doesnt the this refer to the child object? Please enlighten the noob javascripter thanks!

Chopnut
  • 527
  • 7
  • 20

2 Answers2

2

You are using call not bind

One use of Call is to chain constructors (similar to doing super() from within child constructor in OOP languages like JAVA). The child constructor is called which in turn creates Parent object from within Child context.

Bind however will set the required this for the function.

As suggested an explanation of this in javascript can be found in this blog and also in the Stackoverflow question

Community
  • 1
  • 1
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
  • 1
    A reference to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call might be helpful. Also, the `this` keyword can be hard to grasp in JS as its scope is not always clear. This article, http://www.quirksmode.org/js/this.html, may help explain the confusion. – James Jan 11 '17 at 10:41
  • 1
    Thank you :) the reference to call is already added in my answer. I will update with `this`. – Suraj Rao Jan 11 '17 at 10:43
  • Thanks it took a little while for me to understand the 'call()' method! Now im like eureka! cheers – Chopnut Jan 11 '17 at 11:32
1

this is referring the child object only.

Here you are calling Parent function in context of this (i.e child object).

Parent.call(this) is similar to Parent() the only difference is context of calling the method.

ricky
  • 1,434
  • 1
  • 11
  • 23