• javascript中setInterval与setTimeout中this的问题以及对于闭包的一些理解


      最近写代码是碰到一个setInterval中的this指针的问题,代码如下:

    var testClass = function () {
        this.name = "test";
        this.intervalId = null;
    };
    
    testClass.prototype.start = function () {
        this.intervalId = setInterval(this.sayHello, 1000);
    }
    
    testClass.prototype.sayHello = function () {
        console.log("Hello, " + this.name);
    }
    
    var test = new testClass();
    test.start(); //输出“Hello,”
    

      当时第一反应就是this指针出问题了,但是不知道怎么解决,因为setInterval中传入的只是函数的名字,并不是调用,所以我们没法通过保存this的方法来实现,经过多番搜索,找到如下几种解决方案。

      1. 使用bind函数,会有浏览器兼容问题

    this.intervalId = setInterval(this.sayHello.bind(this), 1000);
    

      bind函数类似call函数,都会改变上下文的this,但是bind返回的是函数,而call则会调用函数。

      2.使用闭包,保存this变量

    this.intervalId = setInterval(function () {
    var self = this; return function() { self.sayHello();//有位大神解释闭包,闭包就是可以访问另一个函数内部而它自身外部的变量的函数,js类中的私有变量等就是通过闭包来实现权限控制的 }; }.call(this), 1000);

      个人理解闭包其实就是在一个函数内有可以被外部访问的内部函数,能被访问的内部函数就是闭包例如:

    var a = function () {
        function b() {//不是闭包,因为外部不能访问它
            console.log(b);
        };
        return function c() {//闭包,外部可以访问
            console.log(c);
        }
    }
    

      

      理解的不知道对不对,敬请指教!!

      

  • 相关阅读:
    Windows 10下CUDA及cuDNN的安装 —— Pytorch
    Centos7 python3环境搭建 兼容python2.7
    VMware中Linux虚拟机与Windows主机共享文件夹
    基于阿里云服务器的网站搭建 新手教程
    CVE-2017-11882 漏洞分析总结 新手漏洞分析详细教程
    Linux基本命令 和 Regex 正则表达式
    Shell 编程 基础用法
    Perl 编程 基础用法
    Python3 网络通信 网络聊天室 文件传输
    Ant Design of Angular
  • 原文地址:https://www.cnblogs.com/DARKDD/p/4279595.html
Copyright © 2020-2023  润新知