I'm learning to use object literals in JS, and I'm trying to get a function inside an object to run by calling it through another function in the same object. Why isn't the function "run" running when calling it from the function "init"?
var runApp = { init: function(){ this.run() }, run: function() { alert("It's running!"); } };
You no longer need to specify the function keyword when defining functions inside objects. First option with named functions: const myObj = { myMethod(params) { // ...do something here }, myOtherMethod(params) { // ...do something here }, nestedObj: { myNestedMethod(params) { // ...do something here } } };
An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces. In this tutorial let us learn how to create objects using object Literal with examples.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.
That code is only a declaration. You need to actually call the function:
runApp.init();
Demo: http://jsfiddle.net/mattball/s6MJ5/
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