About
In this code snippet, we’ll learn about objects in Javascript.
Objects can contain other objects, functions, properties and act as a sort of container for them. This is useful for transferring/storing data, modeling real world objects and for grouping a certain set of related functions and variables into one place.
I won’t go into detail about objects or OOP here. I’ll just demonstrate how to make and work with them.
Let’s see how to make an object in Javascript in the example below.
Code:
//Create object with properties and functions.///////////////// let MyPC = { CPU: "Ryzen 9 3900X", RAM : "64GB 3466MHz", GPU : "RTX 2080 SUPER", getSpecs : function() { //If you want to access a property you must reference the object it's in. //If you need it inside the same object it was defined in you can use the "this" keyword. return "CPU: " + this.CPU + " RAM: " + this.RAM + " GPU: " + this.GPU; }, listSpecs: function() { console.log(this.getSpecs()); }, }; //Calling the objects functions. MyPC.listSpecs(); //This is just for a more readable output in the console. console.log("------------------------------------------------"); //Change property value MyPC.CPU = "AMD " + MyPC.CPU; //Accessing properties. console.log(MyPC.CPU); //1. way console.log(MyPC["GPU"]); //2. way /////////////////////////////////////////////////////////////// console.log("------------------------------------------------"); //Adding properties//////////////////////////////////////////// MyPC["HDD"] = "2TB SDD"; console.log(MyPC["HDD"]); /////////////////////////////////////////////////////////////// console.log("------------------------------------------------"); //List all the object members.///////////////////////////////// //1. way, put the object in a for in loop. for(let key in MyPC) console.log("Key: " + key); console.log("------------------------------------------------"); //2. way, get object key as array and iterate through that. myPcKeys = Object.keys(MyPC); for(let key of myPcKeys) console.log("Key: " + MyPC[key]); /////////////////////////////////////////////////////////////// console.log("------------------------------------------------"); //Property getters/setters///////////////////////////////////// const MyScreen = { Resolution : "4K", get resolution() { //Getter implementation in js. //Here you can do some extra logic/validation before getting the value. return this.Resolution; }, set resolution(resolution) { //Setter implementation in js. //Here you can do some extra logic/validation before setting the value. this.Resolution = resolution; } } console.log("My screen resolution is " + MyScreen.resolution); ///////////////////////////////////////////////////////////////