2013-07-17 4 views
-1
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/

+5

* (* getarticles ("JS")') 즉시 * 호출하기 때문입니다. 함수 참조 뒤에'()'를 쓰면 함수가 호출됩니다. 간단한 예제 :'foo (bar())'. 'bar'가 먼저 실행되고 반환 값은'foo'에 전달됩니다. 정말 놀라운 것은 아닙니다. OTOH,'foo (bar)'와 함께'bar' 자체는 인수로'foo'에 전달됩니다. –

+0

http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – steo

+0

왜 함수 대신 변수로 만들겠습니까? –

답변

1

당신은 getarticles을 실행하고 rl.utils.callApadter에 반환 값을 전달하고 있습니다.

그러나 당신이 rl.utils.callApadter 만의 기준을 통과 할 경우 작동합니다 : 그것은 실제로, 라인 (20)에 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); 
0

를 호출되고있어 오히려 전달되지 않고 :

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

을 나는 당신을 생각

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

시도해보십시오.

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