JavaScript and working with objects | by Eldar Jahijagic | May 2022

Javascript engineering: the science behind it

Know these JavaScript concepts to make your life as a programmer easier.

Photo by Glen Wheeler

In addition to my previous two articles on Javascript, I would like to have a thought about objects and working with them, which developers not only in JavaScript but in most languages ​​have to deal with.

JavaScript is built around a simple object-based paradigm. And we all know the items and classes, we’ve probably worked with them our whole career.

An object is a set of properties and a property is an attribute of that object. It is very comparable to we humans. We have our attributes, be it our first name, last name, date of birth, or height and weight.

Objects and object oriented programming are actually inspired by real life objects.

The following examples are a practical guide to working with objects, from the simplest to the most advanced cases.

The usual way to instantiate objects is as follows

# Create new object
const site = {
name: "Medium",
domain: "medium.com",
type: "Writing Platform"
}

But the above is an object initializer, a comma delimited list of properties in braces {}, and is also the shortest syntax. A stricter way would be the following.

# Create new object
const site = new Object();
site.name = "Medium";
site.domain = "medium.com";
site.type = "Writing Platform";

To set the properties themselves, you can use the key name of that property or assign it using square brackets []

site['name'] = "Medium";

The advantage of this approach is that you can set property values ​​using variables.

const propertyName = "name";
const propertyValue = "Medium";
site[propertyName] = propertyValue;

This can be very useful to know and keep in mind when working with collections, mapping lists, objects, types, etc.

Working with objects is not without working with classes.

You most likely know how classes work, so in short – it’s a template for objects, defining properties and functions of an instance, ie. an aura object.

# Classes
class Website {
constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.type = type;
}
// Getter
get url() {
return `https://www.${this.domain}`;
}
// Method
sayHello() {
return `Hello from ${this.name}!`;
}
}
const medium = new Website("Medium",
"medium.com",
"Writing Platform");
const url = medium.url;
const greeting = medium.sayHello();

In the example above, three fields are defined in the constructor himself. This amounts to defining fields alone beforehand.

One interesting thing though is the use of getters which is defined as a get function. It’s not invocable like regular functions but behaves like a property.

Fields or properties can actually be declared before the constructor.

# Fields and Private Fields
class Website {
name;
domain;
#type;

constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.#type = type;
}
}

const medium = new Website("Medium",
"medium.com",
"Writing Platform");

Note how the # The symbol can be used to declare private fields. This field will not be publicly accessible outside of the course.

Generators and the keyword yield is something relatively new in JavaScript. The yield keywords aggregate and yield results from inside a loop – something not so common in other languages ​​but has been around in C# for quite a long time.

# Generator and Yielding results
class Website {
constructor(tabs) {
this.tabs = tabs;
}
*getTabs() {
for(const tab of this.tabs){
yield tab;
}
}

const medium = new Website(["Home",
"Recent","About Us",
"Register"]);

const generator = medium.getTabs();
const tabs = [...generator];

In order to get the values ​​from a generator, we actually need to spread because the function itself returns the type, not the values.

Classes can also be extended in JavaScript.

# Extending Classes
class BaseWebsite {
constructor(name, domain, type){
this.name = name;
this.domain = domain;
this.type = type;
}

sayHello() {
return "Hello!";
}
}

class HttpsWebsite extends BaseWebsite {
constructor(name, domain, type){
super(name, domain, type);
this.scheme = 'https';
}

sayHello() {
let superHello = super.sayHello();
return `${superHello} from ${this.name}`;
}
}

const medium = new HttpsWebsite("Medium",
"medium.com",
"Writing Platform");

const hello = medium.sayHello();

Making use of the extend and super keywords, we are able to extend the properties and methods of an existing class.

In the example above, notice how we can also declare the base function sayHelloreplace it, but continue to use it with the super keyword. The same is done within the constructor as well.

Multiple inheritance is not possible in JavaScript, ie. classes can only extend up to a superclass. The inheritance itself happens at runtime, JavaScript searches the prototype chain of the object, in order to find its declared properties and values.

However, we can take advantage and use Mix-ins to achieve this. Consider the following example

# Mixins
let WalkMixin = superclass => class extends superclass {
walk() {
return "I'm walking!";
}
};
let FlyMixin = superclass => class extends superclass {
fly() {
return "I'm flying!";
}
};
class BaseClass {}
class SampleClass extends WalkMixin(FlyMixin(BaseClass)) {};
const sample = new SampleClass();
console.log(sample.walk());
console.log(sample.fly());

If you inspect the instance sample you’ll notice that its prototype chain contains the two methods defined in the mix-ins above.

Note that this is not a JavaScript feature, but rather a workaround.

Comments are closed.