0

In browser (Chrome) javascript:

var DataModler = {
    Data: { Something: 'value' },

    Process: function() { alert('not implemented.'); },
    Render: function() { alert('not implemented.'); }
}

DataModler.Process = function() {
    // do some data processing, then render it.
    this.Render();   // this == Window, so an exception is thrown.
};

DataModler.Render = function() {
    // render the data.
};

The problem I'm having is, if I set a breakpoint in DataModler.Process(), this is set to Window. I expect this to be set to the object that defines the function, which to my mind is DataModler. If I implement the function within the definition of DataModler, then this == DataModler as I would expect.

So I suppose the question is, how can I allow a function on my object to be replaced but still have this refer to the object on which the function is defined (DataModler)?

Sam Axe
  • 31,472
  • 7
  • 52
  • 80
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – c69 Sep 15 '18 at 00:42
  • @Chase The `this` keyword is a very convenient tool. It can be confusing for beginners, but it allows for much less clumsy code than the alternative. – CertainPerformance Sep 15 '18 at 00:52
  • @CertainPerformance I haven't done many of projects that need to create different objects from same class – Chase Sep 15 '18 at 01:12

1 Answers1

1

As mentioned in c69's comment, you are experiencing this problem due to how the function is actually called. You can write

DataModler.Process = function() {
     ...
}.bind(DataModler);

to ensure that this withing Process is DataModler.

Hero Wanders
  • 2,460
  • 1
  • 4
  • 9
  • By the way, vey much useful information is contained in the answers to this related question: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Hero Wanders Sep 15 '18 at 01:12