Created
September 10, 2017 03:42
-
-
Save StevenJL/09d45278bce69d7742bb75c9874c4229 to your computer and use it in GitHub Desktop.
classes
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
// Before ES6 | |
function Person(name, age) { | |
this.name = name; | |
this.age = age; | |
} | |
// a greeter method on a Person object | |
Person.prototype.greet = function() { | |
console.log('Hi, I am ' + this.name); | |
} | |
// a "class method" on the Person "class" | |
Person.older = function(person1, person2) { | |
return (person1.age >= person2.age) ? person1 : person2 | |
} | |
// With ES6 | |
class Person { | |
constructor (name, age) { | |
this.name = name; | |
this.age = age; | |
} | |
greet() { | |
console.log('Hi, I am ' + this.name); | |
} | |
/* | |
note the static keyword makes the method into | |
a class method, so it's meant to be invoked on | |
the class, not an instance of the class. | |
*/ | |
static order (person1, person2) { | |
return (person1.age >= person2.age) ? person1 : person2 | |
} | |
} | |
// class inheritance | |
class AngryPerson extends Person { | |
constructor (name, age, favorite_expletive) { | |
super(name, age); | |
this.favorite_expletive = favorite_expletive; | |
} | |
yell() { | |
console.log(this.favorite_expletive + '!'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment