0

I'm not all that well versed in JavaScript and I've got a scope problem that I can't find a reference on:

class a
{
  var CommonNameVar;
}

class b extends a
{
  var CommonNameVar;

  function Something(){
     CommonNameVar = "somevalue"; 
  }
}

How do I specifically reference CommonNameVar in b and not a (i.e. reference a specific scope of variables)?

It turns out that I'm also not familiar with unityscript and I've made a rather cardinal mistake of assuming that just because this has a .js on the file, that this is javascript (sound like an old sketch from Bob Newhart).

I'll post a new question formatted correctly for the context and declare this one dead.

Randy Lee
  • 1
  • 4
  • 1
    This is totally invalid syntax. You cannot put `var`s or `function`s in a `class`. Did you mean properties (created in the constructor) and methods? – Bergi Jan 24 '18 at 21:02

1 Answers1

1

You can't hide CommonNameVar from the scope it is declared in. But, to make it available to b, you need to create it as this.CommonNameVar so it becomes an instance property and will inherit, otherwise, it's just a local variable and won't inherit.

The this keyword ensures that you'll always get the value of the property that is associated with the instance.

And, your syntax needs a bit of work as classes declare properties within them, not just "loose" elements.

So, with the code below, when an instance of a is made, this will reference one instance and CommonNameVar will be something and when an instance of b is made, b.CommonNameVar will also be something (because of inheritance), until/unless b.Something() is executed, in which case b.CommonNameVar will then be somevalue, while a.CommonNameVar will remain something.

class a {
  this.CommonNameVar = "something";
}

class b extends a {

  this.Something =  function() {
     this.CommonNameVar = "somevalue"; 
  }
}

this can get considerably more tricky depending on your code structure and you can read about that here.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71