javascript - Object returning as undefined -
if call find function app.count() ok getting correct result when call app.add() getting this.basket undefined. don't why happening?
var app = (function() { var basket = [ { id: 100, price: 10, description: '', name: 'item one', quantity: 10, url: '' }, { id: 200, price: 20, description: '', name: 'item two', quantity: 15, url: '' } ], find = function(item) { for(var = 0; < this.basket.length; i++) { if(this.basket[i].id === item) { return } } return null }, add = function(item) { var itemfound = find(item) }, count = function() { var total = 0; for(var = 0; < this.basket.length; i++) { total = total + this.basket[i].quantity } return total }; return { basket: basket, find: find, add: add, count: count }; })(); app.count() /* works */ app.add() /* returns this.basket undefined */
the problem call of find(item) in add function.
calling find function not use context of app object this, this.basket undefined.
you can check current context this simple console.log(this)
so if want call find function context of app, in add function need call this.find(item)
Comments
Post a Comment