instance javascript code example

Example 1: javascript class

// Improved formatting of Spotted Tailed Quoll's answer
class Person {
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}
	introduction() {
		return `My name is ${name} and I am ${age} years old!`;
	}
}

let john = new Person("John Smith", 18);
console.log(john.introduction());

Example 2: es6 class example

<script>
   class Student {
      constructor(rno,fname,lname){
         this.rno = rno
         this.fname = fname
         this.lname = lname
         console.log('inside constructor')
      }
      get fullName(){
         console.log('inside getter')
         return this.fname + " - "+this.lname
      }
   }
   let s1 = new Student(101,'Sachin','Tendulkar')
   console.log(s1)
   //getter is called
   console.log(s1.fullName)
</script>

Example 3: javascript class static method

// *** JS Class STATIC method ***   

class Animal {
        sayHello() {
            return `${this.constructor.greeting}! I'm ${this.name}!`;
        }
    }

    class Cat extends Animal {
        constructor(name) {
            super(); // connects parent to child/constructor
            this.name = name; //=> need this line otherwise name undefined
        }
        static greeting = 'Feed me';
    }

    class Dog extends Animal {
        constructor(name) {
            super();
            this.name = name; // same output type as above
        }
        static greeting = 'Sigh';
    }

    const run = document.getElementById("run");
    run.addEventListener('click', () => {
        let Garfield = new Cat('Garfield');
        let Snoopy = new Dog('Snoopy');
        console.log(Garfield.sayHello());
        console.log(Snoopy.sayHello());
    })
// output = Feed me! I'm Garfield! Sigh! I'm Snoopy!

Example 4: javascript classes

let Person = class {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}