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.
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"
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;
Lynda.com advises that you next reassign the constructor to B, as follows.
function B() {
A.call(this);
this.y = 2;
}
B.prototype = new A;
B.prototype.constructor = B;
In standard class derivation, there is the nearly universal mistake of deriving from a newly created base class instance (B.prototype = new A). The base class constructor at the very least executes unnecessary code and at the worst may crash without the input arguments that shouldn't have to be artificially created just for the sake of derivation. Furthermore, instance functions of the base class instance becomes part of the derived classes prototype, which is appropriate only by sheer luck.
Lets be clear! If you inherit from a base class instance created by the base class constructor (B.prototype = new A) you are not actually directly inheriting from the base class!! You have created an intermediary in the inheritance chain, namely the base class instance!!! Ouch!!!! This is inefficient because there is an extra depth in seeking inherited property values in the inheritance chain. This depth accumulates every time you make this mistake.
So what's the correct way. Instead of B.prototype = new A you should write
B.prototype = Object.create(A.prototype). This may not have been available in 09. However in 09 there still was
protoProxy = function(myClass)
{
function foo(){};
foo.prototype = myClass.prototype;
return new foo();
}
as a substitute for Object.create. Instead of B.prototype = new A you should write
B.prototype = protoProxy(A) in 09;