Monday, April 14, 2014

Javascript Series for Beginners - Objects

Introduction:

In this post we will talk about how to handle javascript objects.
On the bottom of this post you will find a jsbin that you can use to play with the code snippets below.
This post was inspired by this book: "Javascript: The good parts" by Douglas Crockford

How to create new objects:




How to use inheritance:

Prototype is the mechanism by which objects in javascript inherit properties from other objects.

The prototype link is only used in retrieval. If we look up a property that does not exist in the current object, the prototype link will be used to go up the chain looking if any of the parents has it.

Adding a new property to the parent object will cause to appear in the children but not the other way around.



Reflection and property deletion:

Deleting a property from the child does not impact the parent but it is true the other way around.
Also if you delete a property from the child and the parent has the same property, the parent's value will shine through.


Global scope problem:

One of the big downsides of javascript is that it throws all the objects in the global scope, one way to work around this, is to create a variable that will offer a new scope for your objects and prevent them from conflicting with objects from other applications and librairies.


Your Lab: 

Feel free to play with the code here.

JS Bin


No comments: