I’ve javascript object
var Bucket = function(id) {
this.id = id
this.items = []
}
Bucket.prototype.add_item = function(item) {
//some uniquness checking code here
this.items.push(item);
}
For some reason, when I instantiate the object and try to add an item, I get an error
var bct = new Bucket
bct.add_item(some_item)
'undefined' is not an object (evaluating 'this.items.push')
This error occurs even though the item is getting added to the array of the bucket
console.log(bct.items)
>> [some_item]
I used console.log(this) inside the add_items method and I see two entries being logged from the same line
>Object myjavascript.js:28
>DOMWindow myjavascript.js:28
There are some other libraries included on the page
- Google Analytics
- jQuery
- Colorbox plugin for jQuery
- jQuery Easing
Any ideas what is binding this object to Window?
FOUND IT (Edit)
somewhere else on the page, I was using a jquery ajax call in combination with my object… and it was binding it… sorry for not posting all of the relevant code…
You say “the item is getting added”, but that is irrelevant, because according to your logging you have two calls to the method, one of which is correct. You need to focus on the incorrect one.
Make sure you have a debugger in your browser (e.g. Chrome with the Web Inspector opened), and modify your code like so:
This will automatically pause your code when the erroneous call has occurred. Then, look at the call stack to find out what is calling your
add_itemfunction other than as a method.