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);
  • 相关阅读:
    DAY 42 前端
    DAY 41 mysql
    DAY 40 前端学习
    DAY 39 前端学习
    DAY 38 前端学习
    DAY 37 前端学习
    上传一个桌面
    找到anaconda中自带的qtdesigner,设计ui文件并生成py文件
    python课程:python3的数字与字符串
    python3 偏最小二乘法实现
  • 原文地址:https://www.cnblogs.com/darr/p/5083051.html
Copyright © 2011-2022 走看看