zoukankan      html  css  js  c++  java
  • 嵌套函数中的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);
  • 相关阅读:
    解决jar包冲突
    postman使用记录
    get请求直接通过浏览器发请求传数组或者list到后台
    excel中ppmt/pmt/ipmt的计算方式
    unicode编码与解码
    spring参数拼装
    java内存模型(jmm)
    Mysql事务,并发问题,锁机制-- 幻读、不可重复读(转)
    星空雅梦
    星空雅梦
  • 原文地址:https://www.cnblogs.com/darr/p/5083051.html
Copyright © 2011-2022 走看看