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
  • 21
  • 1
  • 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

1 Answers1

1

I don't think calling "bind" a function on your prototype is a great idea. However, passing

this.start.bind(this)

To setTimeout would solve this issue.

norbertk
  • 348
  • 2
  • 10
  • As much as the solution works, the text of the answer doesn't make sense. – Juan Mendes Dec 08 '16 at 15:17
  • Why don't you think it makes sense? – norbertk Dec 08 '16 at 15:43
  • I can't make sense of `I don't think calling "bind" a function on your prototype is a great idea` – Juan Mendes Dec 08 '16 at 19:59
  • Bind is a function on Function.prototype and all examples online and elsewhere will assume that it's Function.prototype.bind. IMHO, creating a function called bind for your own classes is not a good idea because it can lead to confusion. – norbertk Dec 08 '16 at 20:02
  • Ah, I understand what you mean now. Here's a suggestion, the first line of your post should not be about something that is not related to the problem/bug – Juan Mendes Dec 08 '16 at 20:44
  • Sure, I'll switch my two sentences next time ;) – norbertk Dec 08 '16 at 20:56