Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Passing variables from parent function to child function

I wanted to pass many variables to child functions and that passed variables should also pass on to the next child functions. Passing them each time as parameters is a tedious job. I was wondering what would be the better way to do this in Js. I tried using the this keyword , But not sure if that is the correct way of usage to achieve this.

var scriptConfig = {
  availableOptions: {
    version: "1",
    type: "one",
    status: "free",
  },
  availableCategories: {
    navbar: true,
    hasCoupon: true
  }
};

window.addEventListener('load', function() {
  let options = scriptConfig.availableOptions;
  let version = options.version;
  renderDashboard(options, version);
});

function renderDashboard(options, version) {
  createNavbar(options, version);
}

function createNavbar(options, version) {
  console.log(options);
  console.log(version);
}

Using this

var scriptConfig = {
  availableOptions: {
    version: "1",
    type: "one",
    status: "free",
  },
  availableCategories: {
    navbar: true,
    hasCoupon: true
  }
};

window.addEventListener('load', function() {
  this.options = scriptConfig.availableOptions;
  this.version = options.version;
  this.renderDashboard();
});

function renderDashboard() {
  this.createNavbar();
}

function createNavbar() {
  console.log(this.options);
  console.log(this.version);
}

Can anyone suggest which would be a better way ? Also it would be great if anyone suggest better coding practice for the above lines of code.

like image 564
theFrontEndDev Avatar asked Aug 31 '26 17:08

theFrontEndDev


1 Answers

Using this in global scope (outside class) is not a good idea as it pollute the Window object. I will suggest you to create a class and wrap everything like this:

class Dashboard {
    constructor(config) {
        this.options = config.availableOptions;
        this.version = this.options.version;
    }

    renderDashboard() {
        this.createNavbar();
    }

    createNavbar() {
        console.log(this.options, this.version);
    }
}

var scriptConfig = {
    availableOptions: {
        version: "1",
        type: "one",
        status: "free",
    },
    availableCategories: {
        navbar: true,
        hasCoupon: true
    }
};

window.addEventListener('load', function () {
    const dashboard = new Dashboard(scriptConfig);
    dashboard.renderDashboard();
});
like image 80
Deepak Dixit Avatar answered Sep 02 '26 07:09

Deepak Dixit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!