0

I'm trying to build a reusable Database class with prototypical methods to add items to the class's list array property:

    var Database = function() {
        this.list = [];
    }

    Database.prototype = {
        getBooks: function () {
            $.get("//some.url/books")
            .success(function(res) {
                _.each(res,function(book) {
                    this.list.push({
                        name: book.name,
                        url: book.url,
                        type: "book"
                    })
                })
            });
        }
    }

However, currently I get a warning saying that I cannot push to undefined property list, and I can only assume that I'm not actually .pushing to any Database class instance property, but rather to the prototype property.

So, the question restated: How do you use a prototype method to change an instance's properties?

yellow-saint
  • 668
  • 1
  • 12
  • 31
  • I realise this is slightly duplicative as an answer, but I couldn't wrap my head around the fairly long/abstract answers already provided on StackOverflow/elsewhere. The answer accepted is simple and to the point. – yellow-saint Jan 30 '15 at 15:13

2 Answers2

1

You can store reference to this in variable, like this

 Database.prototype = {
        getBooks: function () {
           var _this = this;
            $.get("//some.url/books")
            .success(function(res) {
                _.each(res,function(book) {
                    _this.list.push({
                        name: book.name,
                        url: book.url,
                        type: "book"
                    })
                })
            });
        }
    }
Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
0

What "this" refers, depends on the situation. Check mdn for more detailed info: MDN this operator

And this thread can help you understand clearly how to pass "this" to another scope: Stackoverflow thread

Community
  • 1
  • 1
raso
  • 71
  • 2