How can one de-reference JavaScript variables when enclosing an outer scope

后端 未结 4 1612
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 22:07

Ok, here\'s a problem script.

var links = [ \'one\', \'two\', \'three\' ];

for( var i = 0; i < links.length; i++ ) {
    var a = document.createElement(          


        
4条回答
  •  失恋的感觉
    2020-12-16 22:49

    I'd stay with your own solution, but modify it in the following way:

    var links = [ 'one', 'two', 'three' ];
    
    function handler() {
        alert( this.i );
    }
    
    for( var i = 0; i < links.length; i++ ) {
        var a = document.createElement( 'div' );
        a.innerHTML = links[i];
        a.i = i; //set a property of the current element with the current value of i
        a.onclick = handler;
        document.body.appendChild( a );
    }
    

    This way, only one function object gets created - otherwise, the function literal will be evaluated on every iteration step!

    A solution via closure is even worse performance-wise than your original code.

提交回复
热议问题