JavaScript闭包理解

一、JavaScript闭包理解/2017-07-19

<script>
    function a(){
        var i = 0;
        var b = function(){
            console.log(i++);
        }
        return b;
    }
    var c = a();
    setInterval('c()', 500); //0 1 2 3 4 5...
</script>

作用域/闭包理解/2017-08-03

<script>
function a(j){
    var i = j;
    var b = function(){
        console.log(i);
    }
    //i++;
    return b;
}
var c = a(0);
c(); //0
a(1); //i值不管怎么变,c里面的i已经锁死了。
c(); //0
c(); //0
</script>

二、JavaScript闭包理解/2017-08-03

<div>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
    <a rel="nofollow" class="mazey-example-a1">Click</a>
</div>
<script type="text/javascript">
var domEles = document.getElementsByClassName('mazey-example-a1');
//正确写法 返回 0 1 2 3...
for (var i = 0, max = domEles.length; i < max; i++) {
    (function(i){ //传入的i被锁定了,与外面的i作用域不一样。
        //debugger;
        domEles[i].addEventListener('click', function () {
            alert(i);
        });
    }(i)); //传入i
}
//错误写法 返回 10
for (var i = 0, max = domEles.length; i < max; i++) {
    domEles[i].addEventListener('click', function () {
        alert(i);
    });
}
</script>

示例: 检查长度/2017-08-08

长度: <input type="text" value="" name="textLen">
<script type="text/javascript">
(function(){
	var textLen = document.getElementsByName('textLen')[0];
	(function(obj){
		obj.addEventListener('blur', function(){
			if(obj.value.length > 20){
				console.log('长度不能超过20位!');
			}
		});
	}(textLen)); //这里的 textLen 与外面的同名 textLen 互不影响.
}());
</script>

三、JavaScript闭包理解/2017-08-08

(function(){
    var data = [];
    for (var i = 0; i < 3; i++){
        data[i] = (function(j){
            return function(){
                console.log(j);
            }
        }(i));
    }
    data[0](); //0
    data[1](); //1
    data[2](); //2
}());

发表评论

您的电子邮箱地址不会被公开。