1

I'm trying to mimic Java-style class inheritance and I thought I'd gotten it. However, I'm having an issue that when I create multiple instance of the same Javascript class, all instances are sort of created the same.

Here is the situation.

I have a Javascript class called Screen:

function Screen(screenName) {
    this.current =  new DataResultSet(); // this is a java class
    this.current.setScreenName(screenName); 
}
Screen.prototype.GetScreenName= function() {
    return this.current.getScreenName();
}
Screen.prototype.GetFieldValue= function(name)  {
    return this.current.getValue(name);
}
// some other functions that can be called that utilize the current object.

This is the inherited class:

function screenSub1() {}
screenSub1.prototype=new Screen("screenSub1");
screenSub1.prototype.GetID = function() { return GetFieldValue("ID"); }
// some other functions that can be called, specific to this class

Now, in my code, if I do

var obj = new screenSub1();
var obj2 = new screenSub1();

The underlying "current" object for both objects are the same! Is there anyway to get around this issue? Thanks!

Julia

Julia S.
  • 39
  • 3
  • One little thing that I noticed: `Screen.prototype.GetScreenName() {` should be `Screen.prototype.GetScreenName = function() {`, if I'm not mistaken (and the same thing for `screenSub1.prototype.GetID`). Also, Javascript convention (as far as I can tell) is to have functions start with a lowercase letter, then camel-case the rest, so something like `getScreenName` instead of `GetScreenName`. – Nic May 12 '15 at 14:44
  • It needs to be `function screenSub1(){ Screen.call(this, "screenSub1"); } screenSub1.prototype = Object.create(Screen.prototype);` – Bergi May 12 '15 at 15:34
  • Bergi, Thanks so much for your response! I'm sorry I made so many mistakes in my posts. I mocked up the code and didn't check. I did search but did not find any answer. But your syntax is correct and I got it working right! Thank you!!!! – Julia S. May 12 '15 at 15:44

1 Answers1

1

As far as I know, you can't (at least not easily, maybe you could find some javascript library that mimics java-like inheritance). Java and Javascript are very different when it comes to inheritance. You can check here if You want to have further information on the subject : https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

francesco foresti
  • 2,004
  • 20
  • 24