prototypal inheritance in JavaScript

One of the things about learning OOP in any programming language is keeping up with the many layers within. 

First, you learn how to write a basic constructor function.

function Song(title, artist, duration) {

  this.title = title;
  this.artist = artist;
  this.duration = duration;
  this.isPlaying = false;

}

Then a function with method as a property.

Then you add prototype functionality so you can share the properties of your functions with other parts of your code.

Then the next (and I believe last thing) to get ones head around is understand prototypal inheritance

Sometimes when you’re writing functions for a project you’re working on you can end up bloating your code by writing the same properties for different instances. What I understand about prototypal inheritance is that it takes away the need to duplicate those properties by sharing them between instances.

In this example I want to share there 2 constructor functions that share similar properties.  Song and Media.  They share properties of title and duration.  The media constructor is to one that will be shared.

First, delete any code that could be shared with the Media constructor

So

function Song(title, artist, duration) {

  this.title = title;

  this.artist = artist;

  this.duration = duration;

  this.isPlaying = false;

}

becomes

function Song(title, artist, duration) {

  this.artist = artist;
}

And then it’s prototype

Song.prototype.play = function() {

  this.isPlaying = true;

};

Secondly the next step is to call Call to prepare the Media function to share the same properties that the Song function used to have. 

Media.call(this, title, duration   can call functions programtically

Now, the function is prepared to take in the same properties but no code is duplicated. It’s much more oganised and dynamic.

Call a function programmatically using a method called call();  specify what function should use as “this”  you can there share parameters as the next argument.

Which takes us to the Third step and the title of this post. Set up protoype chain. This is how one goes about creating inheritance in JavaScript.

Song.prototype = Object.create(Media.prototype);

This tiny piece of code contains a reference to the prototypes of both constructor functions. It copies the references to the Media’s prototype properties and methods to the song prototype creating a prototype chain, completing inheritance between both function.

Advertisements

Does it matter as long as the code just works?

“As long as the code works, it doesn’t matter
I saw a video today when I was studying as I like to do on Treehouse, and i heard some encouraging words that some Treehouse teachers like to say; something on the lines of “if you don’t quite understand, don’t worry”,  which is great, and perfectly okay. I don’t always pick up new concepts as quickly as I’d like.

Especially with my Dyspraxia it can be hard not only to pick up new things but to retain them as I move on to different projects or different areas of web design.

But is that it strictly true?

Is it just okay so long as the code works or is there a need to understand everything you do?  After all, if you know you’ve accomplished some code and got it to do what you want to do then that’s it, right? You can just refer to it again when you need to, or refer to it in your programming languages documentation.

function Dice(sides) {

this.sides = sides;

}
Dice.prototype.roll = function () {

var randomNumber = Math.floor(Math.random() * this.sides) + 1;

return randomNumber;

}
var dice = new Dice(6);

var dice10 = new Dice(10);
console.log(dice.roll === dice10.roll);

I think it’s best to learn as much about what is going on with code as much as I can.

This code demonstrates what goes on with prototypal inheritance.  The simplest way I can put is that 2 instances of an object are created with the hypothetical dice and dice10 instances.

But instead of having them as 2 separate objects, they share values and behaviours between them because they are bound to a roll method in a template method, or to give it its proper name a prototype.

Dice.prototype.roll = function () {

var randomNumber = Math.floor(Math.random() * this.sides) + 1;

return randomNumber;

}

This code will work the same way, working along with the UI code on the other file to generate a random number between 1 and the number of sides.

I think I understand a bit better now what is going on, but for me the learning process is about a little bit more than “if it works, great” because learning code is a tactile experience. You learn more about code by doing code than anything else in life in my opinion.

Object Oriented coding in JavaScript

This would not be the first time I’ve tried to learn OOP, or Object Oriented Programming, it’s a very interesting subject and a lighter subject than trying to cram ecommerce website concepts into my brain.

Something about working with objects fascinates me as someone who likes to keep his code organised, Object Literals are as organised as a programmer can get.  Here’s a basic example of an object literal I wanted to go through.

Dice Roll Calculator

This dice roll calculator example uses the very basics of what Objects have to offer.  An Object, In Javascraft is like little database that is capable of storing data.  It stores an “array” of keys and values that store things in an organised way

var person = {}

The above is the basic skeleton of an object literal.  A variable assigned to a pair of curly brackets.

It looks like a function but it’s different. An object can hold many different types of data; strings, numbers, boo leans and even functions. And a function contained in an object is called a method.  A method can do all the same things a function can. They can have arguments, return values or return nothing at all.

grab the number from the object and display to screen

function printNumber(number) {

var placeholder = document.getElementById(“placeholder”);

placeholder.innerHTML = number;

}

Objects work with functions outside of the scope of that particular object too. In this function for example, a HTML element is being prepared to display a number of a random dice roll, by grabbing an element dynamically by its Id and grabbing the innerHTML.

It stores this into a variable called a parameter. I.e. Number.


program the button click for interactivity

var button = document.getElementById(“button”);

button.onclick = function() {

var result = dice.roll();

printNumber(result);

};

JavaScript knows which events to select by the getElementById method, it works the same way as the printNumber function here. This time, it’s working on the function that triggers a click event.  A variable is assigned and then linked to the click event.

The printNumber function is then called with another variable that passes in the number generated, which will be different every time, always a number between one and six.

The dice.roll() is a reference to a function that performs the random number generation, and since it lives inside an object, it’s called a method. But we haven’t made it yet.

Programming the dice roll in an object literal

var dice = {

sides: 6,

roll: function diceRoll() {

var randomNumber = Math.floor(Math.random() * this.sides) + 1;

return randomNumber;

}

}

This is where the action happens.  We can see how the 3 functions for this program work together.  This object has an integer stored in one key, and a method in another.  Stored inside a variable is a simple but complex calculation. Working from then inside going out, the code generates a random number between 0 and 1 rounds it down, and multiplies it by the value stored in the sides key.  We add 1 to this calculation to make sure that we can get a possible dice roll of 6 displayed on the screen. We then return this value.

How does it all come together?

One way of working it out as thinking of it as a game of pass the parcel.  Each part of the code had a job to do and then passes on that job to the next part of the program.

printNumber has the job of making it possible to see the result of the dice roll in the screen.

Next, interactivity is added to the button.  The code in the click event knows what to do because there’s a call to the dice method, and a result variable is passed in to the printNumber function.

Lastly the object that contains the diceRoll object is created that contains the method that generates the random number for a dice roll.

We could get away with doing this dice roll by using dice.sides rather than this.sides. This is after all a simple example of an interactive script. However this is a very flexible keyword that automatically makes a method the “owner” of that object. So you only have to make changes to the object or method rather than changing the reference to it in your code.

You can see the result of this and the code right here!

Update:  On my Php exploits 

when I last spoke 12 days ago I was talking about my progress in building a php application. An application that involved building a shopping cart, listing products on a webpage and linking these to a PayPal account.

The first part of this application went well.  The CSS was pre built already so there was no problem from a design point of view. And, although I don’t have a working memory for programming I have felt like I’ve at least learned the concepts I need to tackle a basic application in the future. 

Alternatively, I could use my new found php knowledge to build on my experience of building a pure made shopping cart, which interacts with a database and is driven by a good graphical user interface. 

I have a basis now on which to build on if I want to persue this further and code my own e commerce sites.

But then, I tackled a similar problem.  To enhance the php application I’d just built.  This was laden with so many problems.  I’ve not learned as much with this one.  My IT situation for a short time further is still a little up in the air so I’m not downloading files to the computer I’m using (which isn’t my own) until I sort myself out… But that’s by the by.  The main complication is this.  The course runs on an open source localhost server which is a special type of server that runs on a computer hard drive.   So when you’re linking website assets like images and css files, the root url is different.  So uploading files and scripts as a minefield in itself.

So completed the course in the same way as the first. Putting the course code into action and noting down all the theory.

So… That’s that for php for the moment. Until my IT situation is a little more settled I’ve moved onto Object Oriented JavaScript, a topic I’m really looking forward go revisiting.