Call functions from function inside an object (object literal)

纵饮孤独 提交于 2019-12-17 22:34:21

问题


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!");
    }
};

回答1:


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

runApp.init();

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




回答2:


There is nothing magical about the init property of an object, which you happen to have assigned a function to. So if you don't call it, then it won't run. No functions are ever executed for you when constructing an object literal like this.

As such, your code becomes this:

var runApp = {
    init: function(){   
         this.run()
    },
    run: function() { 
         alert("It's running!");
    }
};

// Now we call init
runApp.init();


来源:https://stackoverflow.com/questions/8219008/call-functions-from-function-inside-an-object-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!