What does instance, class, and reference mean in JavaScript?

353 viewsOther

I’m searching online but I’m too… dumb to understand.

😭 TIA.

In: Other

5 Answers

Anonymous 0 Comments

**Class**: A template for making an object. The class itself doesn’t do anything (except “static methods,” which are just functions that can be grouped with a class for organizational purposes).

**Instance**: An object created from a class using `new MyClass()`. Each instance is unique, and multiple references can be held to the same instance.

**Reference**: A variable that holds an instance as it’s value. Setting another variable to the same instance doesn’t copy it, and instead both variables point to the same instance. A real-life use case might be enemies in a game all referencing the same `player` instance, so that as the player’s position changes, all the enemies are using the most up-to-date position in their calculations.

**EX**:

// Create a class. This just acts as a template to create instances
class MyClass {
constructor(value){
this.val = value;
}
}

// Create two separate instances of the same class
const instance1 = new MyClass(2);
const instance2 = new MyClass(3);

console.log(instance1.val); // outputs: 2
console.log(instance2.val); // outputs: 3

// Create a reference to instance1
const myReference = instance1;

// Since ‘myReference’ and ‘instance1’ both point to the same instance, changing the value of one changes the other
myReference.val = 17;

console.log(instance1.val); // outputs: 17, which is the changed value

You are viewing 1 out of 5 answers, click here to view all answers.