Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call functions from function inside an object (object literal)

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!");     } }; 
like image 499
holyredbeard Avatar asked Nov 21 '11 21:11

holyredbeard


People also ask

How do you write a function inside an object?

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 } } };

What is the use of object literals in JavaScript?

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.

What is meant by object literal?

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.


1 Answers

That code is only a declaration. You need to actually call the function:

runApp.init(); 

Demo: http://jsfiddle.net/mattball/s6MJ5/

like image 105
Matt Ball Avatar answered Sep 18 '22 12:09

Matt Ball