ArticleZip > Javascript Class Call Method When Object Initialized

Javascript Class Call Method When Object Initialized

Have you ever wondered how to make sure a specific method gets called as soon as you create an object from a class in JavaScript? Well, you're in luck because today, we're diving into the nitty-gritty details of calling a method when an object is initialized in JavaScript.

Let's start by understanding the basics. When you create an object from a class in JavaScript, the constructor method is automatically invoked. The constructor is a special method that helps initialize the object's properties and set up its initial state.

But what if you want to call a different method right after the object is created? Fortunately, JavaScript provides a straightforward way to achieve this.

To call a method when an object is initialized in JavaScript, you can simply invoke that method in the constructor. Here's a simple example to illustrate this concept:

Javascript

class Example {
  constructor() {
    this.init();
  }

  init() {
    console.log('Method called when object is initialized!');
  }
}

const obj = new Example();

In this example, the `Example` class has a method called `init`, which we want to call when an object is initialized. Inside the constructor, we call the `init` method using `this.init()`.

When you create a new object `obj` from the `Example` class, the `init` method will be automatically called, and you will see the message `'Method called when object is initialized!'` printed to the console.

It's important to note that you can pass arguments to the method being called inside the constructor, just like any other method. This allows you to initialize the object with specific values or perform any necessary setup tasks.

Javascript

class Example {
  constructor(name) {
    this.init(name);
  }

  init(name) {
    console.log(`Hello, ${name}! Object initialized.`);
  }
}

const obj = new Example('John');

In this modified example, the `init` method now takes an argument `name`, which is passed from the constructor. When you create a new object `obj` with the name `'John'`, the message `'Hello, John! Object initialized.'` will be displayed.

By using this approach, you can ensure that a specific method is always called when an object is initialized in JavaScript, allowing you to customize the object's behavior and perform any necessary tasks at the moment of creation.

So, next time you need to trigger a method upon object initialization in JavaScript, remember to include the method call inside the constructor of your class. It's a simple and effective way to make sure your code behaves exactly as intended right from the start.

Happy coding!

×