嵌套函数中的this

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:

var obj = {};
    $.each([1,2,3], function(i, ele){
        obj[ele] = function(){
            console.log(this === obj);//true,obj调用的
        }
    })
    obj[1]();
    console.log(obj);
原文地址:https://www.cnblogs.com/darr/p/5083051.html