2013-06-29 5 views
2

나는 뭔가에 갇혀있어, 어리석은 줄 알았어! 이 코드의 끝에서 괄호 ")()"가 무엇을하는지 알아 내려고합니다. jsFiddle 내가 제거하면 아무 것도 표시하지 않기 때문에. 코드의이 부분에 더 많은 함수를 추가해야하지만 괄호로 인해 오류가 발생합니다.javascript 함수의 정의되지 않은 오류

(function() { 

    var n = 143, 
     duration = 750, 
     now = new Date(Date.now() - duration), 
     count = 0, 
     data = d3.range(n).map(function() { 
      return 0; 
     }); 

    var margin = { 
     top: 6, 
     right: 0, 
     bottom: 20, 
     left: 40 
    }, 
    width = 560 - margin.right, 
     height = 120 - margin.top - margin.bottom; 

    var x = d3.time.scale() 
     .domain([now - (n - 2) * duration, now - duration]) 
     .range([0, width]); 

    var y = d3.scale.linear() 
     .range([height, 0]); 

    var line = d3.svg.line() 
     .interpolate("basis") 
     .x(function (d, i) { 
     return x(now - (n - 1 - i) * duration); 
    }) 
     .y(function (d, i) { 
     return y(d); 
    }); 

    var svg = d3.select("body").append("p").append("svg") 
     .attr("width", width + margin.left + margin.right) 
     .attr("height", height + margin.top + margin.bottom) 
     .style("margin-left", -margin.left + "px") 
     .append("g") 
     .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

    svg.append("defs").append("clipPath") 
     .attr("id", "clip") 
     .append("rect") 
     .attr("width", width) 
     .attr("height", height); 

    var axis = svg.append("g") 
     .attr("class", "x axis") 
     .attr("transform", "translate(0," + height + ")") 
     .call(x.axis = d3.svg.axis().scale(x).orient("bottom")); 

    var path = svg.append("g") 
     .attr("clip-path", "url(#clip)") 
     .append("path") 
     .data([data]) 
     .attr("class", "line"); 

    tick(); 

    d3.select(window) 
     .on("scroll", function() { 
     ++count; 
    }); 

    function tick() { 

     // update the domains 
     now = new Date(); 
     x.domain([now - (n - 2) * duration, now - duration]); 
     y.domain([0, d3.max(data)]); 

     // push the accumulated count onto the back, and reset the count 
     data.push(Math.random()*10); 
     count = 0; 

     // redraw the line 
     svg.select(".line") 
      .attr("d", line) 
      .attr("transform", null); 

     // slide the x-axis left 
     axis.transition() 
      .duration(duration) 
      .ease("linear") 
      .call(x.axis); 

     // slide the line left 
     path.transition() 
      .duration(duration) 
      .ease("linear") 
      .attr("transform", "translate(" + x(now - (n - 1) * duration) + ")") 
      .each("end", tick); 

     // pop the old data point off the front 
     data.shift(); 

    } 
})() 

고맙습니다!

+0

익명 함수를 호출하는 맨 아래에'()'을 괄호로 묶습니다. – antyrat

+0

익명 함수 (괄호 뒤)에 함수를 추가하고 그 뒤에 세미콜론을 추가하려면 함수를 정의 할 수 있습니다. –

+0

괄호 때문에''- 오류가 있습니까? 어떤 코드가 오류를 생성합니까? – David

답변

0

즉시-호출 기능 식 (IIFE)

여기

좋은 읽기 : http://benalman.com/news/2010/11/immediately-invoked-function-expression/

당신은 물론 그것으로 어떤 기능을 추가 할 수 있지만, 때문에 범위 지정, 당신은 동일하거나 더 깊은 범위에서이 함수를 호출 할 수 있습니다 .

예컨대 테스트() 함수 :

+0

다음과 같은 내용을 추가한다고 가정 해 보겠습니다. d3.tsv ("data/dataMulti.tsv", function (error, data) { color.domain (d3.keys (data [0] return key! == "date";})); 대신 test(); 함수를 작성하자마자 오류가 발생합니다! – star

1

http://jsfiddle.net/ZaJZu/ 당신은 익명 함수를 정의했다. 일반적으로 같은 이름 기능 :

function myfunc(){ 
    //code 
} 

를 호출 할 수 있습니다

myfunc(); 

정확히이 () 괄호 doing.It 완료에 익명 함수를 호출합니다. 만약 당신이 이것을 원하지 않는다면, 함수의 이름을 정하고 위의 예제처럼 필요한 곳에서 호출하십시오. (함수 선언에 반대되는) 모든 일의 주위에

Updated fiddle without Parenthesis

+0

답장 해 주셔서 감사합니다. :) 이제 알았습니다. – star

+0

myfunction이라는 이름을 붙였습니다. myfunc()를 호출하고이 익명 작업을 사용하는 대신이 함수를 호출했지만 다른 함수를 추가 할 때 "Uncaught SyntaxError : Unexpected end of input"오류가 표시됩니다. myfunc() 후에 새 함수를 추가했습니다 !! – star

+0

새 기능을 포함하여 해당 코드로 다른 질문하기 –

0

외부 괄호는 함수 표현식에 기능을 켜십시오. 이를 수행하는 다른 방법이 있지만 괄호는 일반적인 규칙입니다. 함수 표현식의 끝에있는()는 즉시 함수 호출을 트리거하는 것입니다.

이것은 재귀 함수이므로 자체 호출 익명 함수가 아닙니다. 이 패턴을 즉시 호출 함수 식 (Immediately-Invoked Function Expression, IIFE)이라고합니다. 일반적으로 모듈 패턴에서 사용되지만 작은 인라인 함수의 결과를 변수에 할당하는 데 상대적으로 자주 사용됩니다. 마지막에()가없는 정규식 이전 호출 함수 표현식은 일반적으로 콜백으로 전달되거나 변수에 할당되거나 메소드를 정의하기 위해 객체 리터럴에서 인라인으로 사용됩니다.

관련 문제