这个函数作为参数传递的问题是什么?

时间:2013-07-17 08:02:11

标签: javascript

var getarticles = function(subject){
      console.log("found your articles about: " + subject);   
}


var rl = rl || {};
rl.utils = (function () {
    var callApadter = function(adapter){
        setTimeout(function() {
            console.log("inside the first timeout");
            adapter
        }, 4000);

    };
    return{
        callApadter: callApadter
    }})();


rl.utils.callApadter(getarticles("JS"));

 setTimeout(function() {
            console.log("this is 4 seconds");
       }, 4000);

有谁能告诉我为什么会立即调用getarticles?

谢谢你们。

小提琴http://jsfiddle.net/UkAeV/

3 个答案:

答案 0 :(得分:1)

您正在执行getarticles并将返回值传递给rl.utils.callApadter

但是,如果您仅将引用传递给rl.utils.callApadter,那么它将起作用: jsFiddle

var getarticles = function (subject) {
    alert("found your articles about: " + subject);
};


var rl = rl || {};
rl.utils = (function () {
    var callApadter = function (adapter) {
        var _this = this,
            _arguments = Array.prototype.slice.call(arguments, 1);
        setTimeout(function () {
            alert("inside the first timeout");
            adapter.apply(_this, _arguments);
        }, 4000);

    };
    return {
        callApadter: callApadter
    };
})();


rl.utils.callApadter(getarticles, "JS");

setTimeout(function () {
    alert("this is 3 seconds");
}, 3000);

答案 1 :(得分:0)

它实际上是在第20行被调用,而不是被传递:

rl.utils.callApadter(getarticles("JS"));

我想你想做点什么

rl.utils.callApadter(getarticles, "JS");

答案 2 :(得分:0)

试试这个:

var getarticles = function(subject){
    return function(){
        console.log("found your articles about: " + subject); 
    }  
}