1

I don't understand, why when I set a function to an object instance, whenever it is accessed from something asynchronous, like setTimeout or a promise, it is undefined. Can someone please explain? Is there a workaround?

Thanks

function Animal() {
    this.check = function () {
        writeln(typeof this.test);
    }
    setTimeout(this.check, 1000); // returns undefined
}

var animal = new Animal();
animal.test = function () {

}
animal.check(); // returns function
  • Your problem can be reduced to: `function A() { this.x = 42; this.foo = function () { console.log(this.x); }; } var obj = new A(); var f = obj.foo; f();` – melpomene Oct 28 '17 at 12:23

1 Answers1

0

Because you're losing context here:

setTimeout(this.check, 1000);

So therefore this inside check will be window, which does not have a test property. Maybe do:

setTimeout(this.check.bind(this), 1000);

Side note: Having dynamically assigned functions is a performance killer and therefore bad style. There's always a better way...

melpomene
  • 79,257
  • 6
  • 70
  • 127
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • @melpoleme thanks, sorry for overriding your changes ;/ – Jonas Wilms Oct 28 '17 at 12:26
  • thanks I get it now. I am using nativescript and I had trouble firing an event from self made objects. I need to trigger an ui update when certain things happen I thought this as an workaround. – Jacklin Heirdom Oct 28 '17 at 12:32
  • @jacklin its hard to give a spefific advise based on the little code we have... – Jonas Wilms Oct 28 '17 at 12:35
  • I have an object like Animal that talks to sqlite via functions that return promises. I'd like to fire an event or call a function like this from inside the resolve promise which would trigger a function in another file, which handles ui, so it could reload. – Jacklin Heirdom Oct 28 '17 at 12:40
  • @jacklin then your solution is acceptable, however i would rather prefer an EventListener pattern, like: `animal.on("update", function(){...});` – Jonas Wilms Oct 28 '17 at 12:52