Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created November 7, 2020 10:49
Show Gist options
  • Save whal-e3/c3e3ea4d2819a38494c0fbf551238e4a to your computer and use it in GitHub Desktop.
Save whal-e3/c3e3ea4d2819a38494c0fbf551238e4a to your computer and use it in GitHub Desktop.
JS constructor inheritance, Object.create(), class
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName}`;
};
const person1 = new Person('John', 'Doe');
console.log(person1.greeting());
// Inheritance ---------------------------------------------
function Customer(firstName, lastName, phone, membership) {
// Inherit the person prototype methods
Person.call(this, firstName, lastName);
this.phone = phone;
this.membership = membership;
}
// Inherit the person prototype methods
Customer.prototype = Object.create(Person.prototype);
// Make customer.prototype return Customer()
Customer.prototype.constructor = Customer;
const customer1 = new Customer('Tom', 'Smith', '333-333-3333', 'Standard');
console.log(customer1);
Customer.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName} welcome to our company`;
};
console.log(customer1.greeting());
// Object.create() ----------------------------------------
const personPrototypes = {
greeting: function () {
return `Hello there ${this.firstName} ${this.lastName}`;
},
getsMarried: function (newLastName) {
this.lastName = newLastName;
}
};
const mary = Object.create(personPrototypes);
mary.firstName = 'Mary';
mary.lastName = 'Williams';
mary.age = 30;
mary.getsMarried('Thompson');
console.log(mary);
console.log(mary.greeting());
// class -------------------------------------------------
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = new Date(dob);
}
greeting() {
return `Hello there ${this.firstName} ${this.lastName}`;
}
// How to calculate age in javascript
calculateAge() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
getsMarried(newLastName) {
this.lastName = newLastName;
}
static addNumbers(x, y) {
return x + y;
}
}
const mary = new Person('Mary', 'Jane', '12-5-1980');
mary.getsMarried('Thompson');
Person.addNumbers(1, 2);
class Customer extends Person {
constructor(firstName, lastName, phone, membership) {
super(firstName, lastName);
this.phone = phone;
this.membership = membership;
}
static getMembershipCost() {
return 500;
}
}
const john = new Customer('John', 'Doe', '444-444-4444', 'Standard');
console.log(john);
console.log(john.greeting());
console.log(Customer.getMembershipCost());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment