1

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

2
  • Did you ever define cardArray in your code? Commented May 26, 2013 at 9:25
  • @SimonM: It's in Parent. Commented May 26, 2013 at 9:37

1 Answer 1

3

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:

Live Copy | Live Source

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.