1

Consider the following code:

var App = function () {
     this.interfaces = [];
};

App.prototype.user = {
    create: function (name) {
        this.interfaces.push(name);
    }
};

var app = new App;

app.user.create('John Doe');

It'll unleash the following error:

Uncaught TypeError: Cannot read property 'push' of undefined

That's because this, in user.create has a different context than App's one. Okay, but how can I access the property interfaces from App in user.create?


Demonstration: JSFiddle

Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96
  • Some previous questions: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site%3Astackoverflow.com%20javascript%20get%20parent%20object –  Mar 18 '15 at 18:46
  • Oh, thank you! It's hard to think to search for `Using 'this' within nested Prototype sub-objects`. =P – Guilherme Oderdenge Mar 18 '15 at 18:48
  • You're welcome. Unfortunately you'll find that the answer is that you can't. The method only knows of the object on which it was invoked. This is worked out dynamically at call time. –  Mar 18 '15 at 18:50

0 Answers0