Object Oriented JavaScript
February 28, 2018
Create
Literal
const p1 = {name: "John"};Object.create
, creates a new object with its prototype set to the given objectconst p1 = {name: "John"};const p2 = Object.create(p1);p1.name; // "John"p2.name; // "John"p1.hasOwnProperty('name'); // truep2.hasOwnProperty('name'); // falseConstructor
A new object is created with its prototype set to the constructor’s prototype
The constructor is then called with its
this
context bound to that new objectfunction Person(name) {this.name = name;}const p1 = new Person('John');// same as// Object.create(Person.prototype)
Encapsulation
es6+
class Person {constructor(name) {this.name = name;}greet() {console.log(`Hello, my name is ${this.name}.`);}}const john = new Person('John');john.greet(); // Hello, my name is John.pre-es6
function Person(name) {this.name = name;}Person.prototype.greet = function() {console.log(`Hello, my name is ${this.name}.`);};const john = new Person('John');john.greet(); // Hello, my name is John
Inheritance
es6+
class Employee extends Person {constructor(name, job, employer) {super(name);this.job = job;this.employer = employer;}greet() {super.greet();console.log(`I am a ${this.job} at ${this.employer}.`);}}const bill = new Employee('Bill', 'cashier', 'Coles');bill.greet();// Hello, my name is Bill.// I am a cashier at Coles.pre-es6
function Employee(name, job, employer) {Person.call(this, name);this.job = job;this.employer = employer;}Employee.prototype = Object.create(Person.prototype);Employee.prototype.constructor = Employee;Employee.prototype.greet = function() {Person.prototype.greet.call(this);console.log(`I am a ${this.job} at ${this.employer}.`);};const bill = new Employee('Bill', 'cashier', 'Coles');bill.greet();// Hello, my name is Bill.// I am a cashier at Coles.