-1

I'm new to Javascript. When I did some objective oriented programming, I want to invoke constructor of super class in a sub-class:

function P(p1, p2) {
  alert(this);
  this.v1 = p1;
  this.v2 = p2;
}

var middleObj = function() {};
middleObj.prototype = P.prototype;

var C = function(p1, p2) {
    P.bind(this, p1, p2);
    P();
}
C.prototype = new middleObj();
C.prototype.constructor = C;

var objChild = new C(1,2);
alert(objChild instanceof P);
alert(objChild.v2);

If I call P() directly in C(), this turns to window, and I can understand that. However, even if I bind this to C(), still I can not get the proper value of this. As a result, the second alert will show undefined because v2 is not initialized properly.

John Doe
  • 3
  • 1
  • If you look more closely at the answers in the linked dupetarget, you'll see that they always use the return value of `bind` (and they explain why). – T.J. Crowder Aug 19 '17 at 11:01

1 Answers1

1

P.bind() will return a function, you need to assign it to your P again. Like this

 P = P.bind(this, p1, p2)

But in this case I suggest you to use just P.call(this, p1, p2);

function P(p1, p2) {
  alert(this);
  this.v1 = p1;
  this.v2 = p2;
}

var middleObj = function() {};
middleObj.prototype = P.prototype;

var C = function(p1, p2) {
    P.call(this, p1, p2);
}
C.prototype = new middleObj();
C.prototype.constructor = C;

var objChild = new C(1,2);
alert(objChild instanceof P);
alert(objChild.v2);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112