Javascript 从对象内部的函数调用函数(对象字面量)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8219008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:10:24  来源:igfitidea点击:

Call functions from function inside an object (object literal)

javascriptfunctionobject-literal

提问by holyredbeard

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"?

我正在学习在 JS 中使用对象文字,并且我试图通过同一对象中的另一个函数调用它来运行一个对象内部的函数。为什么从函数“init”调用时函数“run”没有运行?

var runApp = {

    init: function(){   
         this.run()
    },

    run: function() { 
             alert("It's running!");
    }
};

回答by Matt Ball

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

该代码只是一个声明。您需要实际调用该函数:

runApp.init();

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

演示:http: //jsfiddle.net/mattball/s6MJ5/

回答by Alex Wayne

There is nothing magical about the initproperty 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.

init对象的属性并没有什么神奇之处,您恰好为其分配了一个函数。所以如果你不调用它,它就不会运行。在构造这样的对象文字时,不会为您执行任何函数。

As such, your code becomes this:

因此,您的代码变为:

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

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