mozilla
검색 결과

    New in JavaScript 1.7

    현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

    JavaScript 1.8은 발생자(generator), 반복자(iterator), array  comprehensions, let 표현식(let expression), destructing assignment를 포함한 새로운 기능이 도입되었습니다. 또한, JavaScript 1.6에서 지원했던 모든 기능을 지원합니다.

    JavaScript 1.7은  Firefox 2부터 사용할 수 있습니다.

    이 글에 포함된 코드 예제는 JavaScript 쉘에서 시험했습니다. 쉘을 빌드하고 사용하는 법을 배우려면 JavaScript 쉘 소개를 읽어보세요.

    JavaScript 1.7  사용

    JavaScript 1.7의 새 기능을 사용하려면, HTML이나 XUL 코드에서 JavaScript 1.7을 사용하겠다고 명시해주어야 합니다.

    <script type="application/javascript;version=1.7"/>

    JavaScript shell을 사용한다면, 명령줄에서 -version 170을 사용하거나 다음과 같이 version() 함수를 사용해서 버전을 설정해야 합니다:

    version(170);
    

    현재의 코드가 이들 키워드를 변수나 함수 이름으로 사용하고 있을 수 있으므로, "yield"와 "let"과 같은 새로운 키워드를 사용하는 기능들을 사용하려면 버전을 1.7로 명시해야 합니다. 새로운 키워드를 사용하지 않는 기능들(destructing assignment와 array comprehensions)은 JavaScript 버전을 지정하지 않고 사용할 수 있습니다.

    발생자와 반복자(Generators and iterators)

    반복 알고리듬(목록을 훑거나 똑같은 데이터 셋에 반복 계산을 수행할 때)을 포함한 코드를 개발할 때는 계산을 진행하는 동안 유지해야할 상태 변수가 필요합니다. 전통적으로는 반복 알고리듬의 중간값을 구하기 위해서 콜백 함수를 사용했어야 했습니다.

    발생자(Generators)

    피보나치 수열을 계산하는 반복 알고리듬을 생각해보세요:

    function do_callback(num) {
      document.write(num + "<br>\n");
    }
    
    function fib() {
      var i = 0, j = 1, n = 0;
      while (n < 10) {
        do_callback(i);
        var t = i;
        i = j;
        j += t;
        n++;
      }
    }
    
    fib();
    

    이 코드는 콜백(callback) 루틴을 사용해서 알고리듬의 반복적인 과정을 수행했습니다. 여기서는 각각의 피보나치 수가 콘솔에 출력될 것입니다.

    발생자와 반복자를 사용하면 이 작업을 새롭고 좀 더 좋게 바꿀 수 있습니다. 발생자를 사용한 피보나치 수열을 보겠습니다:

    function fib() {
      var i = 0, j = 1;
      while (true) {
        yield i;
        var t = i;
        i = j;
        j += t;
      }
    }
    
    var g = fib();
    for (var i = 0; i < 10; i++) {
      document.write(g.next() + "<br>\n");
    }
    

    위에서 yield 키워드를  포함한 함수가 바로 발생자입니다. When you call it, its formal parameters are bound to actual arguments, but its body isn't actually evaluated. Instead, a generator-iterator is returned. Each call to the generator-iterator's next() method performs another pass through the iterative algorithm. Each step's value is the value specified by the yield keyword. Think of yield as the generator-iterator version of return, indicating the boundary between each iteration of the algorithm. Each time you call next(), the generator code resumes from the statement following the yield.

    You cycle a generator-iterator by repeatedly calling its next() method until you reach your desired result condition. In this example, we can obtain however many Fibonacci numbers we want by continuing to call g.next() until we have the number of results we want.

    Resuming a generator at a specific point

    Once a generator has been started by calling its next() method, you can use send(), passing a specific value that will be treated as the result of the last yield. The generator will then return the operand of the subsequent yield.

    You can't start a generator at an arbitrary point; you must start it with next() before you can send() it a specific value.

    Note: As a point of interest, calling send(undefined) is equivalent to calling next(). However, starting a newborn generator with any value other than undefined when calling send() will result in a TypeError exception.
    Exceptions in generators

    You can force a generator to throw an exception by calling its throw() method, passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the yield that is currently suspended were instead a throw value statement.

    If a yield is not encountered during the processing of the thrown exception, then the exception will propagate up through the call to throw(), and subsequent calls to next() will result in StopIteration being thrown.

    Closing a generator

    Generators have a close() method that forces the generator to close itself. The effects of closing a generator are:

    1. Any finally clauses active in the generator function are run.
    2. If a finally clause throws any exception other than StopIteration, the exception is propagated to the caller of the close() method.
    3. The generator terminates.
    Generator Example

    This code drives a generator that will yield every 100 loops.

    var gen = generator();
    
    function driveGenerator() {
      if (gen.next()) {
        window.setTimeout(driveGenerator, 0);	
      } else {
        gen.close();	
      }
    }
    
    function generator() {
      while (i < something) {
        /** stuff **/
    
        ++i;
        /** 100 loops per yield **/
        if ((i % 100) == 0) {
          yield true;
        } 
      }
      yield false;
    }
    

    Iterators

    An iterator is a special object that lets you iterate over data.

    In normal usage, iterator objects are "invisible"; you won't need to operate on them explicitly, but will instead use JavaScript's for...in and for each...in statements to loop naturally over the keys and/or values of objects.

    var objectWithIterator = getObjectSomehow();
    
    for (var i in objectWithIterator)
    {
      document.write(objectWithIterator[i] + "<br>\n");
    }
    

    If you are implementing your own iterator object, or have another need to directly manipulate iterators, you'll need to know about the next method, the StopIteration exception, and the __iterator__ method.

    You can create an iterator for an object by calling Iterator(objectname); the iterator for an object is found by calling the object's __iterator__ method. If no __iterator__ method is present, a default iterator is created. The default iterator yields the object's properties, according to the usual for...in and for each...in model. If you wish to provide a custom iterator, you should override the __iterator__ method to return an instance of your custom iterator. To get an object's iterator from script, you should use Iterator(obj) rather than accessing the __iterator__ property directly. The former works for Arrays; the latter doesn't.

    Once you have an iterator, you can easily fetch the next item in the object by calling the iterator's next() method. If there is no data left, the StopIteration exception is thrown.

    Here's a simple example of direct iterator manipulation:

    var obj = {name:"Jack Bauer", username:"JackB", id:12345, agency:"CTU",
              region:"Los Angeles"};
    
    var it = Iterator(obj);
    
    try {
      while (true) {
        print(it.next() + "\n");
      }
    } catch (err if err instanceof StopIteration) {
      print("End of record.\n");
    } catch (err) {
      print("Unknown error: " + err.description + "\n");
    }
    

    The output from this program looks like this:

    name,Jack Bauer
    username,JackB
    id,12345
    agency,CTU
    region,Los Angeles
    End of record.
    

    You can, optionally, specify a second parameter when creating your iterator, which is a boolean value that indicates whether or not you only want the keys returned each time you call its next() method. This parameter is passed in to user-defined __iterator__ functions as its single argument. Changing var it = Iterator(obj); to var it = Iterator(obj, true); in the above sample results in the following output:

    name
    username
    id
    agency
    region
    End of record.
    

    In both cases, the actual order in which the data is returned may vary based on the implementation. There is no guaranteed ordering of the data.

    Iterators are a handy way to scan through the data in objects, including objects whose content may include data you're unaware of. This can be particularly useful if you need to preserve data your application isn't expecting.

    Array comprehensions

    Array comprehensions are a use of generators that provides a convenient way to perform powerful initialization of arrays. For example:

    function range(begin, end) {
      for (let i = begin; i < end; ++i) {
        yield i;
      }
    }
    

    range() is a generator that returns all the values between begin and end. Having defined that, we can use it like this:

    var ten_squares = [i * i for each (i in range(0, 10))];
    

    This pre-initializes a new array, ten_squares, to contain the squares of the values in the range 0..9.

    You can use any conditional when initializing the array. If you want to initialize an array to contain the even numbers between 0 and 20, you can use this code:

    var evens = [i for each (i in range(0, 21)) if (i % 2 == 0)];
    

    Prior to JavaScript 1.7, this would have to be coded something like this:

    var evens = [];
    for (var i=0; i <= 20; i++) {
      if (i % 2 == 0)
        evens.push(i);
    }
    

    Not only is the array comprehension much more compact, but it's actually easier to read, once you're familiar with the concept.

    Scoping rules

    Array comprehensions have an implicit block around them, containing everything inside the square brackets, as well as implicit let declarations.

    Block scope with let

    There are several ways in which let can be used to manage block scope of data and functions:

    • The let statement provides a way to associate values with variables within the scope of a block, without affecting the values of like-named variables outside the block.
    • The let expression lets you establish variables scoped only to a single expression.
    • The let definition defines variables whose scope is constrained to the block in which they're defined. This syntax is very much like the syntax used for var.
    • You can also use let to establish variables that exist only within the context of a for loop.

    let statement

    The let statement provides local scoping for variables. It works by binding zero or more variables in the lexical scope of a single block of code; otherwise, it is exactly the same as a block statement. Note in particular that the scope of a variable declared inside a let statement using var is still the same as if it had been declared outside the let statement; such variables still have function scoping.

    For example:

    var x = 5;
    var y = 0;
    
    let (x = x+10, y = 12) {
      print(x+y + "\n");
    }
    
    print((x + y) + "\n");
    

    The output from this program will be:

    27
    5
    

    The rules for the code block are the same as for any other code block in JavaScript. It may have its own local variables established using the let declarations.

    Note: When using the let statement syntax, the parentheses following let are required. Failure to include them will result in a syntax error.
    Scoping rules

    The scope of variables defined using let is the let block itself, as well as any inner blocks contained inside it, unless those blocks define variables by the same names.

    let expressions

    You can use let to establish variables that are scoped only to a single expression:

    var x = 5;
    var y = 0;
    document.write( let(x = x + 10, y = 12) x+y  + "<br>\n");
    document.write(x+y + "<br>\n");
    

    The resulting output is:

    27
    5
    

    In this case, the binding of the values of x and y to x+10 and 12 are scoped solely to the expression x+y.

    Scoping rules

    Given a let expression:

    let (decls) expr
    

    There is an implicit block created around expr.

    let definitions

    The let keyword can also be used to define variables inside a block.

    Note: If you have more interesting examples of ways to use let definitions, please consider adding them here.
    if (x > y) {
      let gamma = 12.7 + y;
      i = gamma * x;
    }
    

    let statements, expressions and definitions sometimes make the code cleaner when inner functions are used.

    var list = document.getElementById("list");
    
    for (var i = 1; i <= 5; i++) {
      var item = document.createElement("LI");
      item.appendChild(document.createTextNode("Item " + i));
    
      let j = i;
      item.onclick = function (ev) {
        alert("Item " + j + " is clicked.");
      };
      list.appendChild(item);
    }
    

    The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of variable j. Note that it does not work as intended if you replace let by var or if you remove the variable j and simply use the variable i in the inner function.

    Scoping rules

    Variables declared by let have as their scope the block in which they are defined, as well as in any sub-blocks in which they aren't redefined. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:

      function varTest() {
        var x = 31;
        if (true) {
          var x = 71;  // same variable!
          alert(x);  // 71
        }
        alert(x);  // 71
      }
    
      function letTest() {
        let x = 31;
        if (true) {
          let x = 71;  // different variable
          alert(x);  // 71
        }
        alert(x);  // 31
      }
    

    The expression to the right of the = is inside the block. This is different from how let-expressions and let-statements are scoped:

      function letTests() {
        let x = 10;
    
        // let-statement
        let (x = x + 20) {
          alert(x);  // 30
        }
    
        // let-expression
        alert(let (x = x + 20) x);  // 30
    
        // let-definition
        {
          let x = x + 20;  // x here evaluates to undefined
          alert(x);  // undefined + 20 ==> NaN
        }
      }
    

    In programs and classes let does not create properties on the global object like var does; instead, it creates properties in an implicit block created for the evaluation of statements in those contexts. This essentially means that let won't override variables previously defined using var. For example:

    var x = 'global';
    let x = 42;
    document.write(this.x + "<br>\n");
    

    The output displayed by this code will display "global", not "42".

    I copied and pasted this code into an xhtml page

    <script type="text/javascript;version=1.7">
       var x = 'global'; 
       let x = 42; 
       document.write(x + "<br>\n"); 
    </script>
    

    and the output was "42" . I'm not sure "let" works correctly here. Please check. (Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3)

    An implicit block is one that is not bracketed by braces; it's created implicitly by the JavaScript engine.

    In functions, let executed by eval() does not create properties on the variable object (activation object or innermost binding rib) like var does; instead, it creates properties in an implicit block created for the evaluation of statements in the program. This is a consequence of eval() operating on programs in tandem with the previous rule.

    In other words, when you use eval() to execute code, that code is treated as an independent program, which has its own implicit block around its code.

    let-scoped variables in for loops

    You can use the let keyword to bind variables locally in the scope of for loops, just like you can with var.

    var i=0;
    for ( let i=i ; i < 10 ; i++ )
      document.write(i + "<br>\n");
    
    for ( let [name,value] in Iterator(obj) )
      document.write("Name: " + name + ", Value: " + value + "<br>\n");
    
    Scoping rules
    for (let expr1; expr2; expr3) statement
    

    In this example, expr2, expr3, and statement are enclosed in an implicit block that contains the block local variables declared by let expr1. This is demonstrated in the first loop above.

    for (let expr1 in expr2) statement
    for each(let expr1 in expr2) statement
    

    In both these cases, there are implicit blocks containing each statement. The first of these is shown in the second loop above.

    Destructuring assignment

    Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

    The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

    One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.

    This capability is similar to features present in languages such as Perl and Python.

    Examples

    Destructuring assignment is best explained through the use of examples, so here are a few for you to read over and learn from.

    Avoiding temporary variables

    You can use destructuring assignment, for example, to swap values:

    var a = 1;
    var b = 3;
    
    [a, b] = [b, a];
    

    After executing this code, b is 1 and a is 3. Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick).

    Similarly, it can be used to rotate three or more variables:

    var a = 'o';
    var b = "<span style='color:green;'>o</span>";
    var c = 'o';
    var d = 'o';
    var e = 'o';
    var f = "<span style='color:blue;'>o</span>";
    var g = 'o';
    var h = 'o';
    
    for (lp=0;lp<40;lp++)
    	{[a, b, c, d, e, f, g, h] = [b, c, d, e, f, g, h, a];
    	 document.write(a+''+b+''+c+''+d+''+e+''+f+''+g+''+h+''+"<br />");}
    

    After executing this code, a visual colorful display of the variable rotation will be displayed.

    Returning to our Fibonacci generator example from above, we can eliminate the temporary "t" variable by computing the new values of "i" and "j" in a single group-assignment statement:

    function fib() {
      var i = 0, j = 1;
      while (true) {
        yield i;
        [i, j] = [j, i + j];
      }
    }
    
    var g = fib();
    for (let i = 0; i < 10; i++)
      print(g.next());
    
    Multiple-value returns

    Thanks to destructuring assignment, functions can return multiple values. While it's always been possible to return an array from a function, this provides an added degree of flexibility.

    function f() {
      return [1, 2];
    }
    

    As you can see, returning results is done using an array-like notation, with all the values to return enclosed in brackets. You can return any number of results in this way. In this example, f() returns the values [1, 2] as its output.

    var a, b;
    [a, b] = f();
    document.write ("A is " + a + " B is " + b + "<br>\n");
    

    The command [a, b] = f() assigns the results of the function to the variables in brackets, in order: a is set to 1 and b is set to 2.

    You can also retrieve the return values as an array:

    var a = f();
    document.write ("A is " + a);
    

    In this case, a is an array containing the values 1 and 2.

    Looping across objects

    You can also use destructuring assignment to pull data out of an object:

    let obj = { width: 3, length: 1.5, color: "orange" };
    
    for (let [name, value] in Iterator(obj)) {
      document.write ("Name: " + name + ", Value: " + value + "<br>\n");
    }
    

    This loops over all the key/value pairs in the object obj and displays their names and values. In this case, the output looks like the following:

    Name: width, Value: 3
    Name: length, Value: 1.5
    Name: color, Value: orange
    

    The Iterator() around obj is not necessary in JavaScript 1.7; however, it is needed for JavaScript 1.8. This is to allow destructuring assignment with arrays (see bug 366941).

    Looping across values in an array of objects

    You can loop over an array of objects, pulling out fields of interest from each object:

    var people = [
      {
        name: "Mike Smith",
        family: {
          mother: "Jane Smith",
          father: "Harry Smith",
          sister: "Samantha Smith"
        },
        age: 35
      },
      {
        name: "Tom Jones",
        family: {
          mother: "Norah Jones",
          father: "Richard Jones",
          brother: "Howard Jones"
        },
        age: 25
      }
    ];
    
    for each (let {name: n, family: { father: f } } in people) {
      document.write ("Name: " + n + ", Father: " + f + "<br>\n");
    }
    

    This pulls the name field into n and the family.father field into f, then prints them. This is done for each object in the people array. The output looks like this:

    Name: Mike Smith, Father: Harry Smith
    Name: Tom Jones, Father: Richard Jones
    
    Ignoring some returned values

    You can also ignore return values that you're not interested in:

    function f() {
      return [1, 2, 3];
    }
    
    var [a, , b] = f();
    document.write ("A is " + a + " B is " + b + "<br>\n");
    

    After running this code, a is 1 and b is 3. The value 2 is ignored. You can ignore any (or all) returned values this way. For example:

    [,,] = f();
    
    Pulling values from a regular expression match

    When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to pull the parts out of this array easily, ignoring the full match if it is not needed.

    // Simple regular expression to match http / https / ftp-style URLs.
    var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
    if (!parsedURL)
      return null;
    var [, protocol, fullhost, fullpath] = parsedURL;
    

    문서 태그 및 공헌자

    Contributors to this page: teoli, 행복한고니
    최종 변경: teoli,
    사이드바 숨기기