JavaScript class getters and setters

Introduction
I assume you know heard or at least in someone's code seen JavaScript classes. newly introduced classes are much better than functions if your code requires inheritance of constructors "classes"

Brief subintroduction
A class can be made using syntax below given cats as an example

class chat {
    constructor(params) {
        this.name = params.name
        this.color = params.color
    }
    meow() {
        console.log("meow meows" + this. name)
    }
}

Explanation
cat is a class with a constructor and a method named meow note that you can omit the constructor in the above code if you have nothing to initialize

Adding Getters
getters are a piece of code that retrieve properties of a class in class cat they're no user defined getters
JavaScript properties can be retrieved even if you don't use getters for instance

var kitty = new cat({
    name: "tom",
    color: "black"
})

kitty is now an object to retrieve kitty properties you can simply do as you would do with an object

var name = kitty.name // tom
var color = kitty.color // black
kitty.color = "brown whitish"
Kitty.color // brown whitish

Adding custom getters and setters

class chat {
    constructor(params) {
        this.name = params.name
        this.color = params.color
    }
    getName() {
        return this.name
    }
    setName(name) {
        this.name = name
    }
    meow() {
        console.log("meow meows" + this. name)
    }
}

I updated the code by adding two methods getName a getter setName a setter

var kitty = new cat({
    name: "khloe",
    color: "grey"
})

Kitty.getName() // returns khloe

Kitty.setName("angela")
Kitty.getName() // returns angela

Conclusion
I explained on JavaScript classes and gave an example on how to set their properties

Comments

Popular posts from this blog

What is 'this.' keyword in JavaScript

How to iterate array elements using 'for loop' in JavaScript