0

Yesterday, I asked this question: Passing a method for later evaluation and thought that it was as simple as passing a prototype method, rather than calling it immediately after access, resets this to Window. However, today I came across this code today:

sSharing.shareFileWithGroup( node, groupId,  d.resolve, d.reject ); //d is a Angular promise

and when shareFileWithGroup calls its 3rd or 4th argument in its body, it correctly calls any functions previously passed to d.then, i.e. the passed method can locate the original object it was accessed from. What exactly are the rules for setting this when calling a prototype method? The two situations seem to be inconsistent.

EDIT: My understanding is that the passed method d.resolve/reject should not be able to call then functions previously passed as arguments to .then, but it does. My question is how it does it? The only thing I can think of is if promises are built into JS or the methods aren't actually using the prototype and are being put in the constructed object directly.

Tahsis Claus
  • 1,669
  • 1
  • 12
  • 24
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – doldt Sep 30 '15 at 18:30
  • That link implies that the passed promise method won't be able to call then `.then` function arguments, which the answer from my previous question did too. Edited my question to make it clearer what I'm confused about. – Tahsis Claus Sep 30 '15 at 18:37
  • *"What exactly are the rules for setting `this` when calling a prototype method?"* There are no special rules. What `this` refers to depends on how the function is called. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this . – Felix Kling Sep 30 '15 at 18:48
  • Please see my edit. How is the Promise properly being resolved when only it's prototype method is passed in? It shouldn't have `this` set properly and have no memory of which promise it was accessed from originally. – Tahsis Claus Sep 30 '15 at 18:49
  • What makes you think `d.resolve` comes from the prototype? What does `d.hasOwnProperty('resolve')` say? – Felix Kling Sep 30 '15 at 19:38
  • Chrome console showed only `d = Deferred {promise: Promise}` next to the variable (Idk why I thought it showed function properties) and I looked up the source code before thinking of your solution, but accidentally looked at the Promise constructor, not the Deferred constructor (which has similar methods and uses a prototype). But you are right, and Deferred puts methods directly in the object. If you say as much in a comment I'll mark it correct. – Tahsis Claus Sep 30 '15 at 19:57

0 Answers0