views:

382

answers:

2

I want to create sub-class B that inherits from super-class A. my code here:

function A(){
    this.x = 1;
}

B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );

when run it,it show B is undefined.

A: 
B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}

should be

function B(){
    A.call(this);
    this.y = 2;
}
B.prototype = new A;
Luca Matteis
thanks in advance.
chanthou
in advance of what
Luca Matteis
advance of thanks
chanthou
+4  A: 

You must define the B constructor function before trying to access its prototype:

function A(){
  this.x = 1;
}

function B(){
  A.call(this);
  this.y = 2;
}

B.prototype = new A;

b = new B;
console.log(b.x + " " + b.y );  // outputs "1 2"
CMS