2

So, I'm trying to get some traction with prototypes in JavaScript, and I started by trying something basically like the second example in Understanding prototypal inheritance in JavaScript. Currently, I have a bunch of functions that, were I writing in C++, would certainly like to inherit from a parent class; imagine a bunch of functions like

function specificDevice(){
     this.codeNumber = 'abc123';
     this.wrapperDiv = window.parameters.dashboardDiv;
}

I have a whole pile of these functions, and everything worked fine - but the code was kind of silly, since they all shared a lot of members cut and pasted from one to the next. So, per the link above, I did something like

function generalDevice(){
     this.codeNumber = 'abc123';
}

specificDevice.prototype = new generalDevice();

function specificDevice(){
     this.wrapperDiv = window.parameters.dashboardDiv;

     //just to check if this does what I think it does:
     alert(this.codeNumber);
     alert(this.wrapperDiv);
}

And when I make a new instance of specificDevice, the alerts spat out exactly what I expected - 'abc123', and whatever I previously defined as window.parameters.dashboardDiv - perfect! But then, I tried to do what I figured would be the exactly analogous thing on the member variable being pulled from the window object; the above now becomes:

function generalDevice(){
     this.codeNumber = 'abc123';
     this.wrapperDiv = window.parameters.dashboardDiv;
}

specificDevice.prototype = new generalDevice();

function specificDevice(){
     alert(this.wrapperDiv)
}

Disaster - the script falls over with a

'Cannot read property "dashboardDiv" of undefined'.

I'm hoping the problem is obvious to the experts - how come I can make an object that happily recognizes my window.parameters as a thing, but that object's prototype thinks window.parameters doesn't exist?? Thanks in advance.

4

0 回答 0