2015-07-18 30 views
0

试图填充一个JS数组一些动画我做....当我点击我的内网页的链接出于测试目的,下面的JavaScript函数被调用,当我遇到这个问题跑了:为什么我的函数在我将它推到JS数组上时执行?

function testing() 
{ 
    var funcArray = []; 
    var testFunc = function(){console.log("test function");} 

    funcArray.push(function(){console.log("hello there");}); 
    funcArray.push(testFunc()); 
} 

当这个执行时,我得到“测试功能”出现在JS控制台,但不是“你好”。为什么推送预定义的testFunc会导致输出,而不是第一次推送时的内联函数?

+1

删除功能括号。只推名称,'funcArray.push(testFunc);' –

+1

因为您正在使用() –

+0

执行th函数。非常感谢。 – swingMan

回答

6

因为你叫它。

funcArray.push(testFunc()); 

调用 testFunc,然后推结果调用到funcArray的。您可能想要funcArray.push(testFunc);(注意省略了()),它只是将函数引用推送到该数组。

1

因为你在funcArray.push(testFunc());执行它......你想要的是funcArray.push(testFunc);因为testFunc()执行该功能,需要返回并将其推到数组,而testFunc采取实际功能来推动。

相关问题