0

I am trying to use this when invoking a constructor function. I am passing an object literal into the constructor as an argument.

var testView = new View({
  element: '.testEl',
  model: player,
  initialize: function() {
    var self = this;
    setTimeout(function() {
      self.model.set({
        name: 'Billy'
      });
    }, 5000);
  }
}); // view instance

But when I log this inside the object it just gives me View {} but none of the methods inside.

I want to access the model, obviously I am lacking some knowledge here and I am asking why does this not work as expected in the example above?

The view looks like

// View
var View = function(object) {
  object.initialize.call(this);
  this.element = document.querySelector(object.element);
  this.element.innerHTML = object.model.get('name');

  setTimeout(function() {
    this.element.innerHTML = object.model.get('name');
  }, 6000);
};
Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135
  • What `this` refers to depends on how `initialize` is called. Since it's not called at all in the sample you show, we can't really help you in detail. See the duplicate for general information which may help. – deceze Feb 23 '16 at 09:55
  • Ok that kind of makes sense now, I updated the OP. – Michael Joseph Aubry Feb 23 '16 at 09:56
  • 1
    OK, better now. Though the problem is obvious then: `this` refers to the `this` in `View`, meaning to the new instance of `View`. What you want to refer to instead is the `object`. You can't have your cake and eat it too; `this` either refers to `object` or the `View` instance, it can't be both. – deceze Feb 23 '16 at 09:59
  • Sweet, but wouldn't that mean I would at least see the constructor methods when logging `this`? – Michael Joseph Aubry Feb 23 '16 at 10:01
  • What "constructor methods" exactly? – deceze Feb 23 '16 at 10:05
  • Isn't `this` in the within the constructor function the constructor itself. So that means `this` inside the initialize method should have access to `this.element` but it doesn't. Sorry I am not so familiar with how `call()` exactly works. – Michael Joseph Aubry Feb 23 '16 at 10:12
  • 1
    Yes, the `this` you're passing to `initialize` is the `this` that you're attaching `element` to. However, you're only doing this *after* you call `initialize`. – deceze Feb 23 '16 at 10:15
  • Aha makes sense now :) So I can have my cake and eat it too. I just need to call initialize after everything. – Michael Joseph Aubry Feb 23 '16 at 10:16

0 Answers0