JavaScript Note

2015-06-11  本文已影响0人  westmoor

how to pass loop variables in JavaScript callback?

JavaScript is NOT block scope, the loop always ends before callback executed if written in java-like way.
solution

for (var i = 0; i < max; i++){
    (function(index){
        // do your stuff here
        // use the index variable as it is assigned the 
        // the value of i.
     }(i)
var myArray =["I", "you","turtle"];
alert(myArray.indexOf("turtle")) // will return 2;
return myArray.splice(myArray.indexOf("turtle"), 1) // will return turtle and delete it from array

splice() 是从array中删除所选element 并返回
slice() 是用来选择element

for (var key in p) {
  if (p.hasOwnProperty(key)) { // to check if it is not in prototype
    alert(key + " -> " + p[key]);
  }
}
var name = "The window"
var object = {
    name: "My object",
    getName: function(){
        return this.name;
    }
};
console.log(object.getName()); logs My object
var func = new Object();
func.method = object.getName; // "this" will refers to immediate context
console.log(func.method()); // logs undifined
func.name = "hello";
console.log(func.method()); // logs hello

there are two ways to fix this problem

// first is to use a bind
func.method = object.getName.bind(object);
console.log(func.method()); //logs My object
//
// second is to use closure;
var name = "The window";
var object  = {
    name: "My object",
    getName: function(){
        var that = this;
        return function(){
            return that.name;
        };
    }
};
var func = object.getName();
console.log(func());
function assignHandler(){
    var element = document.getElementById("someElement"); // reference to DOM element 
    element.onclick = function(){
        alert(element.id); // reference to activation object 
    };
}

This code creates a closure as an event handler on element, which in turn creates a circular reference. The anonymous function keeps a reference to the assignHandler() function's activation object, which prevents the reference count for element from being decremented.
solution:

function assignHandler(){
    var element = document.getElementById("someElement");
    var id = element.id;
    element.onclick = function(){
        alert(id);
    };
    element = null;
}
(function(){
    // block code here;
})();

and this can be used for private scopes

function outputNumbers(count){
    (function(){
        for (var i = 0; i < count; i++) {
            alert(i);
        }
    })();

    alert(i); // cause an error
}

This technique is often used in the global scope outside of functions to limit the number of variables and functions added to the global scope. to avoid naming collisions.

上一篇 下一篇

猜你喜欢

热点阅读