Skip to content
Related Articles
Open in App
Not now

Related Articles

How to access state in a function outside of the class ?

Improve Article
Save Article
  • Last Updated : 02 Feb, 2023
Improve Article
Save Article

In the context of a function defined outside of a class, state refers to the data associated with an instance of the class being passed as an argument to the function. The function can access and modify this data by referencing the object’s instance variables.


  • Define a class with the desired state as class variables.
  • Create an instance of the class.
  • Define a function outside of the class.
  • Within the function, access the state using the instance name followed by the variable name (i.e. instance_name.variable_name).
  • If the function needs to modify the state, pass the instance as an argument and use it to update the variable.
  • If the function needs to return the state, return the variable or the instance.
  • Use the function and instance to access or update the state as needed.

Example 1: The below example will illustrate the above approach:


class MyClass {
    constructor() {
        this.x = 20;
    randomMethod() {
        this.x = 30;
function randomFunction(obj) {
const myObj = new MyClass();



The above example shows that randomFunction is defined outside of the MyClass() class. When it is called and passed an instance of MyClass as an argument, it can access the x state of the object (which is initially set to 20). The randomMethod method is then called on the myObj object, which modifies the x state to 30. When randomFunction is called again and passed the modified myObj object as an argument, it outputs the new value of x (30).

Example 2: This the another example showing above approach:


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <p>Click on button to access state in a
      function outside of the class.</p>
    <p id="message"></p>
    <button id="myBtn">Click me</button>
    let message = "Hello World";
              .innerHTML = message;
    const myFunction = (message) => {
              .addEventListener("click", () => {



In this example, the myFunction function can access the value of the message variable because it is passed as an argument when the function is called inside the addEventListener function of the button.

This way, you can access the state in a function outside the class.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!