Skip to content

Instantly share code, notes, and snippets.

@nickylimjj
Created July 22, 2016 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickylimjj/427f2463ae025e86fe58931bde308f6b to your computer and use it in GitHub Desktop.
Save nickylimjj/427f2463ae025e86fe58931bde308f6b to your computer and use it in GitHub Desktop.
Nodejs: Classes - Syntactic sugar for function constructors and prototypal inheritance
// classes.js
'use strict'
var Person = class Person {
// function Person (args) {}
constructor (firstname, gender) {
this.firstname = firstname
this.gender = gender
}
// function.prototype.introduce () {}
introduce () {
console.log(`${ this.designation[this.gender] }. ${ this.firstname } says hello! `)
}
}
Person.prototype.designation = {
m: 'Mr',
f: 'Mdm'
}
// utils.inherit(Singaporean, Person)
var Singaporean = class Singaporean extends Person {
constructor( firstname, gender, favSinglishWord) {
// Person.call(this)
super(firstname, gender)
this.favSinglishWord = favSinglishWord
}
// overwrite function
introduce () {
console.log(`${ this.designation[this.gender] }. ${ this.firstname } says hello ${ this.favSinglishWord }!`)
}
}
module.exports = {
Person : Person,
Singaporean : Singaporean
}
var Person = require('./classes').Person
var Singaporean = require('./classes').Singaporean
var jane = new Person('jane','f')
var jon = new Person('john', 'm')
jane.introduce()
jon.introduce()
var tim = new Singaporean('tim','m','lah')
tim.introduce()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment