The problem of "this confusion in JavaScript

Source: Internet
Author: User
Tags setinterval

functioncountdown (seconds) { This. _seconds =seconds;} Countdown.prototype._step=function() {Console.log ( This. _seconds); if( This. _seconds > 0) {         This. _seconds-= 1; } Else{clearinterval ( This. _timer); }}; Countdown.prototype.start=function() {     This. _step ();  This. _timer = SetInterval (function() {         This. _step (); }, 1000);};NewCountdown (). Start ();

When you run this code, an exception will appear "this._step is not a function". This is a very popular "Thisdisorder " problem in JavaScript: the This in a function that SetInterval repeatedly executes is inconsistent with the external this. There are three ways to solve this problem.

Closed Package

Add a variable that points to the desired this, and then place the variable in the closure:

function () {    varthis;      This . _step ();     this. _timer = SetInterval (function() {        self._step ();     );};
Bind function

ES5 the new "bind" method for the function type can change the "this" of the function (which actually returns a new function):

function () {    this. _step ();     this. _timer = SetInterval (function() {        this. _step ();    }. Bind (this), +);};
Arrow functions

The arrow function is a new language feature in ES6, which, on the surface, simply makes the encoding of the anonymous function shorter, but in fact it hides a very important detail--the arrow function captures this as its ownthis in the context. In other words, the inside of the arrow function is consistent with this one outside of it. So, here's the solution:

function () {    this. _step ();     this. _timer = SetInterval (() + =        {This. _step ()    ; );};

The problem of "this confusion in JavaScript

Related Article

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.