Skip to content

JavaScript class variables | Example code

  • by

There are no such class variables in JavaScript. There are some frameworks out there that simulate a classical inheritance pattern, but technically it all boils down to constructor functions and prototypes.

You can do this:

PersonProto = { // the "class", or prototype
    fname: "thisfname"
};

function Person() { // the constructor function
    this.instanceVar = 'foo';
}

Now, connect the constructor to the prototype:

Person.prototype = PersonProto;

And, voilà:

var a = new Person();
alert(a.fname);

A class variable is an important part of object-oriented programming (OOP) that defines a specific attribute or property for a class.

JavaScript class variables

Simple example code.

This is still a proposal and it would look as follows:

class A {
   property = "value";
}

BTW, when you want to access a class property (i.e. an own object property) you’ll still need to use this.property:

<!DOCTYPE html>
<html>
<body>
  <script>

    class A {
      property = "value";

      constructor() {
        console.log(this.property);
      }
    }

    var test = new A();
    console.log(test.property);
  </script>

</body>
</html> 

Output:

JavaScript class variables

3 ways to define a variable in JavaScript class:

1)To define properties created using a function(), you use the ‘this’ keyword

function Apple (type) {
    this.type = type;
    this.color = "red";
}

To instantiate an object of the Apple class, set some properties you can do the following:

var apple = new Apple('macintosh');
apple.color = "reddish";

2) Using Literal Notation

var apple = {
type: “macintosh”,
color: “red”

}

In this case, you don’t need to (and cannot) create an instance of the class, it already exists.

apple.color = "reddish";

3) Singleton using a function

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
}

So you see that this is very similar to 1 discussed above, but the way to use the object is exactly like in 2.

apple.color = "reddish";

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading