JavaScript Objects; From Sass to Class

Woohoo!!! I completed the Codecademy JavaScript course! Wrapping up the course dealt specifically with JavaScript objects and an intro to OOP. I was especially happy about learning inheritance in objects as well as prototypes.

Inheritance reminds me a little bit of a SASS “extends” in the idea that a class declaration can inherit from another class.

.link {
font-size: 1em;
padding: 0.5em;
}
.button {
@extends .link;
background: red;
}
// Which would produce the following CSS:
.link, .button {
font-size: 1em;
padding: 0.5em;
}
.button {
background: red;
}

So, while we’re on classes, here’s what the above Sass example might look like using Class inheritance in JavaScript. This is achieved using “prototype” which literally works by extending its parent object.

// Define a Link class
function Link() {
this.fontSize = “1em”;
this.padding = “0.5em”;
}
// Define a Button class
function Button(background) {
this.background = background;
}
// Set Button’s prototype to be a new instance of Link
Button.prototype = new Link();
// Create a button object
var myButton = new Button(“red”);
console.log(myButton);

By setting Button’s prototype to be a new instance of Link we were able to create a new button object myButton without having to also specify key:value pairs for the other properties we would need.

Like what you read? Give Justin Seiter a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.