JavaScript does not find a variable when using settimeout, SetInterval (1)

Source: Internet
Author: User

We call settimeout in a scope or within a class of our own definition, and setinterval often encounter errors that cannot be found for a variable. For example, the following:
 window.onload = function   () {manager.init ();};  var  manager = function   () {Slef  = this;         this . Name = "Manager" ;    SetInterval ( this . Timermonitor, 1000 function   () {Console    . log ( this  .name); }}
Let's look at the results under Chrome: We didn't print the manager as expected. Because this.name this variable is undefined state. So how do we solve this problem? Just put SetInterval (Timermonitor, 1000) and change to setinterval (function () {Self.timermonitor ()}, 1000); The complete code is as follows:
function () {    manager.init ();}; var manager = {    function() {        self =this;         this. Name = "Manager";        SetInterval (function() {self.timermonitor ()}, ()}    ,        function  () {        Console.log (this. Name);    }}

Let's look at the results of the operation under Chrome:

This time the this.name variable is printed correctly. The problem is solved, the problem is coming, why is it so good? Update the blog later to explain why.

JavaScript does not find a variable when using settimeout, SetInterval (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.