0

Is it possible in this code:

var this_module = {

    foo: 'something'

    promise: new Promise (function(resolve, reject) {

        resolve (this.foo);
        })
}

to set the value of this to be this_module so that this.foo will be foo: 'something'?

rabbitco
  • 2,790
  • 3
  • 16
  • 38

2 Answers2

4

Not without calling new Promise after the object was created:

this_module.promise = new Promise(function(...) { ... }.bind(this_module));

This is basically the same issue as covered in Self-references in object literal declarations : you are trying to access the object instance during initialization, which is simply not possible.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thank you very much @Felix Kling. I received two solutions which I both find to be very helpful. So I would prefer to check mark both. Unfortunately this is technically not possible. I have given your answer an up vote in a try to "reward" both answers - unsure if that breaks some kind of Stackoverflow protocol. One disadvantage with your otherwise simpler and cleaner solution: In a module with a lot of properties there is a lot of "lines" between stating the property and setting its value. For more details on my choice see comment to the other answer. – rabbitco Mar 07 '16 at 12:56
1

You need to use the getter syntax:

var this_module = {

    foo: 'something'

    get promise() {
       return new Promise (function(resolve, reject) {
          resolve (this.foo);
       }.bind(this))
    }
}

It happens because you don't have the object itself initialized when adding the property to it promise: new Promise().
In a getter, the object is initialized already and the callback can be bind with this object (see more about .bind()).

Note: This will return a new promise every time the property is accessed (thanks @Felix).

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
  • 1
    Note that this will return a new promise every time the property is accessed. – Felix Kling Mar 04 '16 at 14:31
  • @FelixKling It's easy to store the promise in an internal property, if it's necessary. – Dmitri Pavlutin Mar 04 '16 at 14:33
  • Right, but it's still important to note that :) – Felix Kling Mar 04 '16 at 14:37
  • Thank you @DmitriPavlutin! I discovered that I actually need the property to return a new promise each time it is accessed - and for that your `getter` was the right solution. As I bonus I also found out that a lazy `getter` was a perfect solution for another problem I was struggling with. So all in all I have check marked this answer for being the most helpful to me personally even though the solution presented by Felix Kling also solved the problem - in a more simple way and with a cleaner syntax. – rabbitco Mar 07 '16 at 12:50
  • @rabbitco You're welcome. In many cases generating each time a new promise is needed. – Dmitri Pavlutin Mar 07 '16 at 13:28