Skip to content

JavaScript class properties

  • by

The class object itself doesn’t have any properties. The properties are created in the constructor, and nothing can tell you what properties the instance will have from looking at the class object.

class ClassMates{
	constructor(name,age){
    	this.name=name;
      	this.age=age;
    }
  	displayInfo(){
    	return this.name + "is " + this.age + " years old!";
    }
}

let classmate = new ClassMates("Mike Will",15);
classmate.displayInfo(); 

JavaScript class properties

Simple example code.

class Student {
    constructor(name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    get age() {
        return 2018 - this.birthDate;
    }

    display() {
        console.log(`name ${this.name}, birth date: ${this.birthDate}`);
    }
}

console.log(Object.getOwnPropertyNames(new Student));

Output:

JavaScript class properties

How to create methods for JavaScript class properties?

Answer: Use another class or object, and transform the constructor arguments.

const makeShade = arr => ({
  rgba: (opacity = 1) => `rgba(${arr.join(", ")}, ${opacity})`
});

class Color {
  constructor(dark, light, white, id) {
    this.dark = makeShade(dark);
    this.light = makeShade(light);
    this.white = makeShade(white);
  }
}

const pink = new Color(
  [226, 155, 166], [240, 214, 219], [250, 245, 246]
);

//get rgba css string for a shade
console.log(pink.light.rgba());

Source: stackoverflow.com

Note: Class properties are still a proposal in JavaScript and may not be fully supported in all environments without transpilation using tools like Babel.

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

Your email address will not be published. Required fields are marked *