Object Oriented Javascript (a Series ..)

Object Oriented Javascript (a Series ..)

A somewhat simplified & straightforward series about object oriented javaScript concepts. (part

Objects and Programming

Everything in the world is an object !!! (except people of course), and in programming it is very helpful to model software like real-world objects, because it gives us that much needed structure, an it gives us great insight into how the various part of our software interacts with each other.

OOJS BASICS

Before we go on, i would like to share one very useful statement about JavaScript that helped in my journey of understanding this concepts

~ Nearly everything in JavaScript is an object ~

And with that, we can begin !!!

source code for this series can be found at https://github.com/jriffs/OOJS-TUTORIAL

Object literals

Object literals are a form of object declaration which is very common and widely used.

const obj1 = {} //empty object

const obj2 = { // initialized object with properties in a name:value pair
    name: ['Bob', 'Smith'],
    age: 32,
    gender: 'male',
    interests: ['music', 'skiing'],
    farewell: function() {
        this.color = 'red'
        alert('goodbye !!!')
    }
}

As shown above, objects have properties, and those properties come in name:value pairs.

Accessing object properties

The Dot notation

obj2.age // -> 32

The Bracket notation

obj2['age'] // -> 32

Both ways of accessing object properties can be chained depending on the number of sub-namespaces.

setting new / updating object properties

obj2.height = 15 // sets a new property called 'height'
obj2.gender = 'female' // updates the 'gender' property

The 'this' keyword

Basically the 'this' keyword points to the object to which that particular 'this' keyword is enclosed. An example is given below.

obj2.bio = () => {
    alert(`${this.name[0]} ${this.name[1]} is ${this.age} years old. He likes ${this.interests[0]} and ${this.interests[1]}.`)
} // here 'this.name[0]' is the same as 'obj2.name[0]'

a further example on 'this' keyword

obj1.conversation = function() {
    let preamble = 'i spoke to the first guy, and he said' 
    obj2.response = function() {
        return `my name is ${this.name[0]}, goodbye !!`
    }           
    alert(`${preamble} "${obj2.response()}"`)
}

though the obj2.response is created inside the obj1.conversation method, the this keyword in the obj2.response method is enclosed in that method which is a property of the object obj2, hence it points to obj2.

obj1.conversation() // -> i spoke to the first guy, and he said "my name is bob, goodbye !!"

Note - using the 'this' keyword in methods initialized with arrow function returns undefined, so always use the 'function' declaration.

And with that we conclude the first part of our series, hope this helps someone somewhere.

Stay Tuned for the next part of the series.