Monday, October 29, 2018

javascript - Entire JS inside one global variable?




I've got a school assignment of creating an app and one of the restrictions were that only one global variable was allowed, named "App". So I need to put the whole JS inside this variable.



I thought of doing something like:



App = function() { this.test = () => alert("test"); }


And then calling it with App.test().




But this doesn't work, the error I'm getting is:




Uncaught TypeError: App.test is not a function at HTMLLIElement.onclick (index.html:25)




Am I doing something wrong?


Answer



You need to define your app in a variable as an object and then you can use those members of the object such as:




// Object creation
window.App = {};


Then you add more properties like functions or variables and use it later inside of that variable.



window.App.test = function() {
alert('test');
}


window.App.variable = 'my variable';

console.log( App.test() );
console.log( App.variable );


Another thing is you can omit the word window from App.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...