Fun with Objects and This


Whenever you have an object in Javascript, you can create a lot of useful things using this. Have a quick demo.

Lets say you work on a music streaming service. You might have an array of objects with songs, each object looking like this:

var myjam = {
    title: "Behind The River",
    artist: "Talisco",
    file: "behind_the_river.flac"

And now you want to play that song. A nice way to add this function via this.

It’s easy.

Firstly, we setup our function.

function Song (title, artist, file) {
    this.title = title;
    this.artist = artist;
    this.file = file; = function () {
        // "playing" the song
        return "Now playing " + this.title + " by " + this.artist;

Now, let’s setup our song again so we can use it.

var myjam = new Song("Behind The River", "Talisco", "behind_the_river.flac");

// returns an object similar to the one above, but with the function 'play'

And if we want to play the song, we just have to call the function!;

// returns "Now playing Behind The River by Talisco"

Quite easy. I really like this (pun intended). And of course you can still get the strings from the object, like myjam.title.