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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With