GithubHelp home page GithubHelp logo

ticker's Introduction

Ticker

Почему this._i не увеличивается. Как исправить? В примере:

function Ticker() {
    this._i = 0
    };
Ticker.prototype = {
    tick: function() {
            console.log(this._i++);
            }
};
var ticker = new Ticker();

setInterval(ticker.tick, 1000);

this._i не увеличивается из-за потери контекста: setInterval получил функцию ticker.tick равной

ƒ () {
   console.log(this._i++)
}

но не её контекст.

Есть несколько вариантов получения нужного результата:

  1. Используем встроенный метод bind для привязки контекста
function Ticker() {
   this._i = 0
   };
Ticker.prototype = {
   tick: function() {
           console.log(this._i++);
           }
};
var ticker = new Ticker();

setInterval(ticker.tick.bind(ticker), 1000);

Здесь мы указываем, что к функции ticker.tick привязывается контекст ticker 2. Оборачиваем вызов ticker.tick в анонимную функцию:

function Ticker() {
    this._i = 0
    };
Ticker.prototype = {
    tick: function() {
            console.log(this._i++);
            }
};
var ticker = new Ticker();

setInterval(
    function (){
        ticker.tick()
    }, 1000);

здесь ticker достаётся из замыкания. 3. С помощью вспомогательной функции HelpUs():

function Ticker() {
   this._i = 0
   };
Ticker.prototype = {
   tick: function() {
           console.log(this._i++);
           }
};
var ticker = new Ticker();

function HelpUs(func, context){
   return () => func.apply(context, arguments)
   }

setInterval(HelpUs(ticker.tick, ticker), 1000);

С помощью вспомогательной функции HelpUs получаем "обёртку", которая передаёт вызов в func (ticker.tick), с теми же аргументами, но фиксированным контекстом context (ticker)

ticker's People

Contributors

gusssar avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.