> For the complete documentation index, see [llms.txt](https://hemantajax-2.gitbook.io/javascript-step-by-step/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hemantajax-2.gitbook.io/javascript-step-by-step/class.md).

# Class

* Classes are object blueprints
* Each instance of a class has its own unique properties&#x20;
* One class => One / Many objects&#x20;

## Example: Basic Class

Classes are defined with the `class` keyword, and instantiated with the `new` keyword

```javascript
class Person {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    introduce(){
        return "Hello, I'm " + this.name;
    }
}

var p = new Person("Hemant");
console.log(p.introduce());
```

## Inheritance

* Classes can inherit properties from other classes&#x20;
* Child classes inherit all method and properties

```javascript
class Vehicle {
    speed: number;
    constructor(speed){
        this.speed = speed;
    }
}

class Car extends Vehicle {
    drive() {
        console.log("Going " + this.speed + " MPH!");
    }
}

class Honda extends Car{
    drive() {
        super.drive();
        console.log("Honda Car " + this.speed + " MPH!");
    }    
}

var h = new Honda(190);
h.drive();
```

## Public / Private Modifiers

* Class properties are public by default&#x20;
* Public properties can be accessed through `object[propName]`&#x20;
* Private properties cannot be accessed externally

```javascript
class Lock {
    private passcode : number;

    constructor(passcode : number){
        this.passcode = passcode;  
    }

    unlock(code : number){
        if (code===this.passcode){
            console.log("Unlocked!");
        }
    }
}

var lock = new Lock(7777);
console.log(lock.passcode); // compile-time error
lock.unlock(7777); // ok
```

## Accessors (Getters/Setters)

* Let you define special functions for accessing or setting a variable&#x20;
* Looks like a normal public variable from outside the class

```javascript
class Hamster{
    private _name: string;
    get name () : string {
        return this._name;
    }
    set name (name : string) {
        this._name = name;
    }
}

var c = new Hamster();
c.name = "Hemant"; // set as property
console.log(c.name); // ( called as property not as function )
```

&#x20;**Note:** setters/getters are supposed to be used as property not as function

## Static Properties

Static properties belong to the class itself, and not an instance

```javascript
class Ruler{
    static centimeterToInch : number = 12;
    convertCentimeters(cm:number) {
        return cm * Ruler.centimeterToInch;
    }
}

var ruler = new Ruler();
console.log(ruler.convertCentimeters(3)); // 36
console.log(Ruler.centimeterToInch); // 12
```
