Javascript Class Declarations

Introduction

Class declarations begin with the class keyword followed by the name of the class.

class Person {/*ww  w  . ja  v  a 2 s  . com*/

    // equivalent of the PersonType constructor
    constructor(name) {
        this.name = name;
    }

    // equivalent of PersonType.prototype.sayName
    sayName() {
        console.log(this.name);
    }
}

let person = new Person("CSS");
person.sayName();   

console.log(person instanceof Person);     // true
console.log(person instanceof Object);          // true

console.log(typeof Person);                    // "function"
console.log(typeof Person.prototype.sayName);  // "function"
```

Class declarations, unlike function declarations, are not hoisted.

All code inside of class declarations runs in strict mode automatically.

All methods are non-enumerable.

Calling the class constructor without `new` throws an error.

Attempting to overwrite the class name within a class method throws an error.




PreviousNext

Related