I found myself in an interesting situation. I am using an object literal to represent a product in the real-world. Now each product has a length associated to it for shipping purposes. It looks something like this:
var product = {
name: 'MacBook Pro 15 Inch',
description: 'The new macbook pros....',
length: 15
height: 15
Weight: 4
}
This this works fine. But for products that have unknown length they default to length -1.
Again this works fine, until you try to do this:
console.log('Product has the following properties');
_.each(product, function(val, key) {
console.log(key + ":" + val);
});
No keys will be printed for a product that has a length of -1. Why? Well because internally underscore uses the length attribute, that every object in Javascript has to loop over all the attributes of the passed in object. Since we overwrote that value, it is now -1, and since we start looping at i = 0, the loop will never be executed.
Now for the question, how can I prevent the length property from being overridden? Best practices to prevent this from happening would also be appreciated.
try this: