9. OOPS in JavaScript
Object-Oriented Programming (OOP) lets you model real-world things using objects and classes. JavaScript supports OOP with both prototypes and ES6 classes.
9.1 Core Concepts
Classes & Objects
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
let dog = new Animal('Rex');
dog.speak(); // Rex makes a noise.
Constructors
Special method for initializing new objects.
9.2 Prototypes
Every object has a prototype. Methods and properties are inherited via the prototype chain.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hi, ' + this.name);
};
let p = new Person('Sam');
p.greet();
this, call, apply, bind
this refers to the current object. Use call, apply, and bind to control this.
function show() { console.log(this); }
show.call({x:1}); // {x:1}
9.3 Advanced OOPS
Class Expression
const MyClass = class { };
Inheritance
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let d = new Dog('Buddy');
d.speak(); // Buddy barks.
Getter & Setter
class User {
constructor(name) { this._name = name; }
get name() { return this._name; }
set name(val) { this._name = val; }
}
let u = new User('Ann');
console.log(u.name); // Ann
u.name = 'Eve';
Hoisting in Classes
Class declarations are not hoisted. You must declare before use.
Next: Asynchronous JavaScript