Reputation: 8066
I have some javascript code shown below
function extends(Child, Parent) {
var F = function() {
};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function Parent() {
this.cardArray = [];
}
function Child() {
}
then I call
extends(Child , Parent);
var a=new Child();
it reports
a.cardArray is undefined
Your comment welcome
Upvotes: 1
Views: 124
Reputation: 1074959
Two issues there:
First, you can't use extends
as a function name (unless you use strict mode and only run the code in environments that support strict mode). It's a reserved word in loose mode. (It's not currently used and isn't likely to be, but it's reserved.)
The second, and more sigificant, is that you haven't called Parent
anywhere, and so naturally that property has never been added to the object. You need to call Parent
from within Child
to get the things it sets up, and you need to do it such that this
is correct within the call to Parent
. We can do that via Function#call
, which lets us call a function specifying what this
should be (in our case, we want it to be the same as this
within the call to Child
):
function Child (){
Parent.call(this);
}
So in total, and with the incorrect (but harmless) semicolons removed, and with the extends
changed to something that isn't reserved, and with the indentation made consistent, we get:
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function Parent (){
this.cardArray=[];
}
function Child (){
Parent.call(this);
}
extend(Child, Parent);
var a = new Child();
console.log("typeof a.cardArray = " + typeof a.cardArray);
...which shows "typeof a.cardArray = object", which is correct.
Note that truly effective JavaScript inheritance requires (for now) a fair bit of plumbing. You have a lot of it there, but not all of it. (Calls to parent methods are awkward, for instance.) I've done a very small library called Lineage
that does all the plumbing for you, FWIW.
Upvotes: 3