Javascript Class Expressions

Introduction

Here's the class expression:

let Person = class {

    // equivalent of the PersonType constructor
    constructor(name) {/*from w w  w.  ja va  2 s  . co m*/
        this.name = name;
    }

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

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

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

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

Named Class Expressions

let Person = class Person2 {

    // equivalent of the PersonType constructor
    constructor(name) {//from  w w w  . j av a 2  s . c  o  m
        this.name = name;
    }

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

console.log(typeof Person);        // "function"
console.log(typeof Person2);       // "undefined"

 



PreviousNext

Related