ES6

OOP in JavaScript ES5 & ES6

Written by  on September 26, 2015

I’ll have one advice, to learn JS : just forget what you know about programming.

That especially includes the this keyword, OOP, Classes, Objects, Methods …. If you can clear such notions from your mind, you will be ready to understand what JS is :

var person = {"name" : "Bobby"}
var greet = function (end) {
 console.log("Hello " + this.name + end);
}
greet.call(person, "!");
//Prints : Hello Bobby!

person uses the built-in type Object : that is a associative array, an association of unique keys with they respective values. In the example, person has a property (key) called ‘name’ that references the value “Bobby”.

greet uses the built-in type Function : a bit of code that can be invoked. You can notice than the function has a property call that let us apply a value to the this keyword and other expected arguments. We’re setting the value of this inside greet and we’re calling it. Without using Function.call the value of this.name would have been undefined.

That’s what’s important to understand first : in JS a Function is a callable Object we can bind data to.

If one can grasp this concept he will save some time and headache learning JS by trying to apply notions like OOP. It has never been designed in such ways.

OOP is still possible IN ES5. Nevertheless hackey since we need to emulate/redesign it and it might be limited compared to what is possible in other OOP languages.

JS ECMAScript 5 ‘s OOP

In ES5,  one way is to use Functions to define classes and we define their prototypes to emulate inheritance.

Read more…