0

I'm trying to write some JS object. Getting stuck on something, I don't understand how contexts work. Here is a simple example :

var MyApp = function(el) {
    this.el = el;
};

MyApp.prototype.bind = function() {
    window.setTimeout(this.start, 300);
}

MyApp.prototype.test = function(msg) {
    console.log(msg);
}

MyApp.prototype.start = function() {
    console.log(this); // Returns the window context
    this.test('Hello'); // Doesn't work, of course.
}

var myapp = new MyApp(el);
myapp.bind();

Problem is when calling the start method, I'm in the window context because of the window.setTimeout. Is there a way to fix this or is it a pattern design issue?

Thanks ;)

Axel
  • 35
  • 3
  • One of the solutions on that question talks about using [`bind`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) to fix the issue - don't confuse it with your own `bind` function you've defined. – James Thorpe Dec 08 '16 at 14:57
  • This was already marked as a duplicate, but @GillesC is correct from what I can tell. You can apply the correct context with `window.setTimeout(this.start.bind(this), 300);`. – Joseph Marikle Dec 08 '16 at 14:59
  • Well I might have found something: – Axel Dec 08 '16 at 15:01
  • Hello, yeah sorry, I was posting my own reply but you were faster. – Axel Dec 08 '16 at 15:02

0 Answers0