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);
  • 相关阅读:
    maven编译时GBK错误
    生产环境中,通过域名映射ip切换工具SwitchHosts
    Java中的Filter过滤器
    Notepad++远程连接Linux系统
    MySQL 创建帐号和对表的导入导出
    XML 初识
    MySQL 字符集的设置
    C# 委托
    肖申克的救赎
    C#指针 常用手段
  • 原文地址:https://www.cnblogs.com/darr/p/5083051.html
Copyright © 2011-2022 走看看