OOP in JavaScript
Everything in JavaScript is an object or can be treated like one. Learn about familiar JavaScript objects to get a deeper understanding of why objects are useful. An object’s states are represented by attributes/properties and it’s behaviors are represented by methods.
DOM is an object.
DOM elements are objects.
Arrays are objects.
Array.length
Array.pop()
Array.concat()
Object Literals
Object literals are an important foundation for understanding object-oriented programming in JavaScript. Encapsulation describes consolidating an object’s properties and methods into a package and attaching it to a variable.
Dot Notation
const ernie = {
animal: 'dog',
age: '1',
breed: 'pug',
sound: 'Woof!',
bark: function(){
console.log(this.sound);
}
}
ernie.age; // 1
ernie.age = 2;
ernie.breed; // `pug`
ernie.bark(); // `Woof!`
ernie.color = 'black';
Bracket Notation
const ernie = { ... }
ernie['age'] // 1
ernie['breed'] // `pug`
ernie['bark']() // `Woof!`
var prop = 'breed';
ernie[prop]; // `pug`
this
const player1 = {
name: 'Ashley',
color: 'purple',
isTurn: true,
play: function(){
if(this.isTurn === true) {
return this.name + " is now playing!";
}
}
}