首页 > 其他 > 详细

嵌套函数中的this

时间:2015-12-28 16:54:27      阅读:103      评论:0      收藏:0      [点我收藏+]
function countDown(){
    var self = this;
    var doWork = function(){
        console.log(this);//window
        console.log(self);//span
    };
    doWork();
};
$(".outer").each(function(index, item){
    countDown.call(this);
})

直接doWork,使上下文丢失了。嵌套函数中的this变成window。

手动改正:

function countDown(){
    var self = this;
    var doWork = function(){
        console.log(this);//span
        console.log(self);//span
    };
    doWork.call(this);
};
$(".outer").each(function(index, item){
    countDown.call(this);
})

原来和经常用的点击事件的这个是一样的。。。

$("#btn1").on("click", function(){
        btn1();//window
    });
    $("#btn2").on("click", btn1);//btn
    function btn1(){
        console.log(this);
    }

修正后的:

function countDown(){
    var timer = null;
    var seconds = $(this).attr("data-seconds");
    var self = this;
    var doWork = function(){
        if(seconds > 0){
            seconds--;
            $(this).html(seconds);
        }else{
            window.clearInterval(timer);
        }
    };
    timer = window.setInterval(function() {
        console.log(this);//window
        doWork.call(self);//改变作用域
    }, 1000);
};
$(".outer").each(function(index, item){
    countDown.call(this);
})

 

嵌套函数中的this

原文:http://www.cnblogs.com/darr/p/5083051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!