DEV Community

Sourav Bandyopadhyay
Sourav Bandyopadhyay

Posted on

2

Instance and Non-instance properties

In JavaScript, instance properties are properties that belong to an instance of a class or an object, while non-instance properties are properties that belong to the class or the object itself.

  • Instance properties are defined inside the class constructor using the "this" keyword, and they can be accessed and modified using the dot notation on an instance of the class:
class Person {
  constructor(name, age) {
    this.name = name; // instance property
    this.age = age;   // instance property
  }
}

const john = new Person("John", 30);
console.log(john.name); // "John"
john.age = 31;
console.log(john.age); // 31
Enter fullscreen mode Exit fullscreen mode
  • Non-instance properties, on the other hand, are defined outside the class constructor or object literal using the class name or object name, respectively. They can be accessed and modified using the dot notation on the class or object itself:
// Class example
class Person {
  static species = "Homo sapiens"; // non-instance property
}

console.log(Person.species); // "Homo sapiens"

// Object example
const person = {
  name: "John",
  age: 30,
};

person.gender = "Male"; // non-instance property
console.log(person.gender); // "Male"
Enter fullscreen mode Exit fullscreen mode

In the above example, Person.species is a non-instance property of the Person class, while person.gender is a non-instance property of the person object. Non-instance properties are typically used to define values that are shared among all instances of a class or all objects of a certain type.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay