JavaScript Objects and Classes

5/5 - (1 vote)

What is an Object in Javascript?

Everything else that is not a Primitive type is an Object type.

In JavaScript, an object is a standalone entity, an unordered collection of related data in the form of “key: value” pairs.
keys can be variables or functions and are called properties (for variables) and methods (for functions).

About JavaScript prototypes

In object-oriented programming, classes are a model through which we can create instances.
In a class-based inheritance model, classes are the main way that we relate objects to each other.
Read here about JavaScript classes.

On the other hand in JavaScript, which has a prototype-based inheritance model, all objects are descended from Object.

All objects inherit methods and properties from Object.prototype, although they may be overridden.
With prototypical inheritance, we talk about prototypes and children instead of classes and instances.

JavaScript prototype example

To understand how it prototype works in JavaSCript, suppose we have the following object in JavaScript, with properties and methods:

let car = {
	color: "red",
	year: 1990,
	age: function(){
		let date = new Date();
		return date.getFullYear() - this.year;
	}
}

console.log(car.age()); //32

This car object can serve as a prototype for any other car objects that we want to create.
To do this we can use a built-in function in JavaScript called Object.create.

Object.create is used to create children from a prototype object.

let anotherCar = Object.create(car);

console.log(anotherCar.color); //red
console.log(anotherCar.age()); //32

This new car is now a child of the car prototype.

This means that anotherCar has all the properties and methods that the car prototype had.

Now we can access the properties of the prototype from the child object.

But the important part is that we’re allowed to override these properties that our anotherCar inherited from the car prototype as well as add new properties:

anotherCar.color = "blue";
console.log(anotherCar.year); //1990
console.log(anotherCar.color); //blue

Careful!!!
If we make any changes to the prototype we create an object from, those changes are going to be reflected in the child object, in our case anotherCar.

car.year = 2000;
console.log(anotherCar.year); //2000

The exception is if we have overridden one of the inherited values in the child object, changes to those values on the prototype won’t change the values on the child.

car.color = "black";
console.log(anotherCar.color); // is still blue

Also if we delete one of these overriding properties by the child object, the value of that property won’t be undefined.

delete car.color;
console.log(car.color); // undefined
console.log(anotherCar.color); // is still blue

Understanding the Prototype Chain in JavaScript

When we try to access a property in an object, JavaScript first will check to see if the object has that property as one of its own properties.

If it does, JavaScript will tell us whatever the value of that property is in the object itself.

If it doesn’t, however, JavaScript will then check the object’s prototype to see if the prototype has that property as one of its own properties.

If it doesn’t, it will move on to the prototype’s prototype and so on until it either finds that property or reaches the end of the prototype chain.

The end of the prototype chain for all objects in JavaScript is the base object prototype Object.prototype or {}.

About Object.getPrototypeof()

To find out what the prototype is for any given object we can use the JavaScript built-in Object.getPrototypeof function:
If we call this function it returns the object’s prototype.

So if we were to call it on anotherCar object, it would give us the car object that we used as a prototype with Object.create.

let car = {
	color: "red",
	year: 1990,
	age: function(){
		let date = new Date();
		return date.getFullYear() - this.year;
	}
}

let anotherCar = Object.create(car);

console.log(Object.getPrototypeOf(anotherCar)); // {color: 'red', year: 1990, age: ƒ}

But if we call it on the car prototype, it would give us the base object prototype, since we created it using the curly-brace syntax.

let car = {
	color: "red",
	year: 1990,
	age: function(){
		let date = new Date();
		return date.getFullYear() - this.year;
	}
}

let anotherCar = Object.create(car);

console.log(Object.getPrototypeOf(car)); // {}

Object data types characteristics

  • Objects are mutable by default
  • Objects have unique identities and are compared by reference
  • Variables hold references to objects

Javascript objects are reference data types

A JavaScript Object is a reference data type.

Variables that are assigned by reference points to a location in memory, which is accessible only by javascript itself.

The variables don’t actually contain the value.

So when you do:
objA = objB
you only copy the reference pointer to object in memory.

Object Properties

JavaScript objects can have properties, which define their characteristics.

An object property can be any valid JavaScript string or anything that can be converted to a string, including the empty string.

Properties vs. Keys vs. Values in JavaScript

The term property usually refers to the key/value pair that describes a member of an object.
“property” (is the whole thing, part of an object), “property name” (the string used as the key) and “property value” (the stored data). For example:

height : 10 => property(key/value pair)
height => key or property name
10 => value or property value

What is the difference between object keys with quotes and without quotes?

JavaScript objects do not contain single or double quote marks around the keys when no spacing is used in the key name. So, if there’s spacing in the key name, quotes are used.

Accessing Object Properties

You can access the properties of the object in the following ways:

  • objectName.propertyName
  • objectName[“propertyName”]
  • Or if an object have multiple properties, You can use the bracket notation with for…in to iterate over all the enumerable properties of an object.
var book1 = {
    title: "First book title",
    author: "John Doe",
    pages: 500,
    type: "Fiction",
    "e book": "yes"
};
console.log(book1.title);
console.log(book1["title"]);
//Result
First book title
First book title

Object.length Has a value of 1.

Object.prototype
Allows the addition of properties to all objects of type Object.

How to use object destructuring to get object properties?

Using Object Destructuring we can more easily extract variables from the properties of an object.

Suppose we have the object below.

let obj1 = {
    name: "xyz",
    age: 20,
    color: "blue",
    height: 175,
}

We can access the properties one by one, like obj1.name or using Object Destructuring, we can easily create variables from the properties of an object let {name, age} = obj1.

let {name, age} = obj1
console.log(age); //20

If we need we can add default values into the Object Destructuring syntax if we are not sure that the object has that property.

let {name, age, weight = 72} = obj1
console.log(weight); //72

If we do not add a default value for the weight, the result will be undefined.

If we want a name of a given variable to be different than the property name in the object

let {name: newName, age, weight = 72} = obj1
console.log(newName);

The order is the object’s key, colon, and then what we want the variable name to be.

How to access nested properties in an object?

let obj1 = {
    name: "xyz",
    age: 20,
    color: "blue",
    height: 175,
    inventory: {
        wallet: 1, 
        cards: 3, 
        keys: 1,
    }
}
let {inventory: { wallet } } = obj1;
console.log(wallet); //1

Object methods

Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

var book1 = {
    title: "First book title",
    author: "John Doe",
    pages: 500,
    type: "Fiction",
    "e book": "yes",
    getAuthor: function(){
        return this.author;
    }
};

Accessing Object Methods

You access an object method with the following syntax:
objectName.methodName()

var book1 = {
    title: "First book title",
    author: "John Doe",
    pages: 500,
    type: "Fiction",
    "e book": "yes",
    getAuthor: function(){
        return this.author;
    }
};
console.log(book1.getAuthor());
//Result 
John Doe

this is the book object that “owns” the getAuthor() function.
this.author means the author property of this object.

Object methods examples

Object.assign()
Copies the values of all enumerable own properties from one or more source objects to a target object.

JavaScript provides some nice utility functions that we can use to work with Objects more easily. Read here about JavaScript built-in Object Functions

Object.create()
Creates a new object with the specified prototype object and properties.

How to create an object in JavaScript?

You can create an object:

  1. using an object initializer { … }
  2. using a constructor function and then instantiate an object invoking that function in conjunction with the new operator

1. with figure brackets { … } with an optional list of properties (“key: value” pairs)

The key is a string, called “property name“.
The property names can be strings or numbers. If the property name contains several separate words, the property names must be enclosed in quotes.

var book1 = {
    title: "First book title",
    author: "John Doe",
    pages: 500,
    type: "Fiction",
    "e book": "yes"
};

2. Using Constructor

Object()
The Object constructor creates an object wrapper for the given value.
Objects of the same type are created by calling the constructor function with the new keyword:

function Book(title, author, pages, type){
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.type = type;
};
book2 = new Book("Second book", "Mike", 299, "Non fiction");
//Result
Non fiction

Also, You can declare Strings, Numbers, and Booleans as Objects, like:

var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object

The String global object is a constructor for strings or a sequence of characters.

It’s not recommended to do this, because they complicate your code and slow down the execution speed.

Copying Objects in JavaScript

What is the difference between window, screen, and document in Javascript?

window Object and document Object are not the same things!

Window Object

The window Object is the first thing that gets loaded into the browser, the root of everything. This window object has the majority of the properties like length, innerWidth, innerHeight, location, history, etc

Document Object

The document Object is the top DOM object, like your HTML, PHP, or other documents that will be loaded into the browser. The document actually gets loaded inside the window object and has its own properties like title, URL, cookie, etc

Screen Object

The screen Object just contains information about the screen dimensions. Screen properties width and height are the full-screen dimensions.

Sets in JavaScript

Set objects are collections of unique values. Set can store any types of values whether primitive or objects.
Set in ES6 are ordered! Read more here about sets in JavaScript.

Creates a new Set object

Set()

Set Methods

  • Set.prototype.add() – It adds new elements with a specified value at the end of the Set object.
  • Set.prototype.delete() – It deletes an element with the specified value from the Set object.
  • Set.prototype.clear() – It removes all the element from the set.
  • Set.prototype.has() – It returns true if the specified value is present in the Set object.
  • Set.prototype.values() – It returns all the values from the Set in the same insertion order.
  • Set.prototype.forEach() – It executes the given function once for every element in the Set, in the insertion order.

About JavaScript classes

JavaScript isn’t class-based!

JavaScript doesn’t actually have classes. What appears to be classes in JavaScript, is just a facade for something else behind the scenes.

JavaScript uses prototypes. Read here about JavaScript prototypes.
However we can use classes in JavaScript as follows:

How to define a class in JavaScript?

We can define a class using the class keyword.

class Car {
    constructor() {
     //instance setup
    }
}

The constructor can take as many arguments as we need in order to set up the instances of the class.

class Car {
	constructor(year, color){
		this.year = year;
		this.color = color;
	}
}

What mean “this” keyword in JavaScript?

The “this” keyword is used inside a class definition to refer to a specific instance of that class.

The “this” keyword refers to what’s called the current execution context.
This means that when we use the “this” keyword inside a function, it doesn’t matter where the function is defined, it matters more where the function is called from.

We can create instances of our Person class using the new keyword in JavaScript.

    let firstCar = new Car(1994, "red");

We can access the member variables which we created nefore using . or []

    console.log(firstCar.color); //red
    console.log(firstCar['color']); //red

How to define public and private member variables in JavaScript?

At this time in JavaScript, there are no private class variables!

Is a proposal to define public variables up at the top of the class definition (like in Java) and private variables are defined by putting a hash mark before the variable name.

class Car {
    color; // Public variable
    #year // Private variable
    ....
    }
}

Until another one, at this point, a way to denote that a given variable should be treated as private is by putting an underscore before the variable name like:

class Car {
    constructor(year, color){
	this._year = year;
	this.color = color;
    }
}

About JabaScript class methods

How to create a class method?

class Car {
	constructor(year, color){
		this.year = year;
		this.color = color;
	}

	age(){
		let date = new Date();
		return date.getFullYear() - this.year;
	}
}

let firstCar = new Car(1994, "red");

console.log(firstCar.age()); //28

JavaScript static methods

JavaScript allows us to create static methods.

A static method is a method that belongs to the class itself instead of individual instances of the class.

How to create a static method?

To create a static method put the keyword static before the method name.

Careful!!! Do not use the this keyword in static methods, because a static method don’t belong to any specific instance of a class.

We can call a static method using the ClassName.methodName().

JavaScript Class Inheritance

To create a class inheritance, use the extends keyword.

A sub-class inherits all the methods from the parent class.

class Car extends Vehicle {
...
}

An instance of a subclass is considered an instance of all its super classes.

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net