Created
July 22, 2016 06:09
-
-
Save nickylimjj/427f2463ae025e86fe58931bde308f6b to your computer and use it in GitHub Desktop.
Nodejs: Classes - Syntactic sugar for function constructors and prototypal inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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