Open In App

How to define instance and non-instance properties ?

In this article, we will try to understand how we could define as well as create an instance and non-instanced properties in JavaScript.

Before analyzing instance and non-instanced properties let us first see the following syntax of creating a class in JavaScript since both instance and non-instance properties are defined on the class itself.



Syntax:

class class_name {
    constructor() {
        // variables.....
        // or...
        // methods.....
    }
    // Other variables or methods.....
}

Now that we have seen a basic structure/syntax which we could use for creating a class in JavaScript let us use this syntax for understanding as well as creating a class-based instance and non-instance properties.



Following the static example of a class which we have created by using the above syntax (Note in the below example we will not be accessing any variable declared inside the class, it’s just the demo class shown for understanding).

class Car {
    constructor () {
        this.car_name = "Ford";
    }
}

Instance Properties:

Example: The following example will help us to understand the above-stated facts in a much better and efficient manner-




<script>
    class Person {
        constructor() {
            this.Name = "ABCD";
        }
    }
    let person = new Person();
    console.log(person.Name); // Output: ABCD
    console.log(Person.Name); // Output: undefined
</script>

Output:

ABCD
undefined

Non-instance Properties:

Example: The following example will help us to understand the above-stated facts in a much better and efficient manner-




<script>
    class Person {
        static Name = "ABCD";
    }
  
    let person = new Person();
    console.log(person.Name); // Output: undefined
    console.log(Person.Name); // Output: ABCD
</script>   

Output:

undefined
ABCD

Article Tags :