How do you convert an object to a string?
It started out simple enough:
var s = obj.toString();
Ooops. But wait. What if an object has a toString
key inside of it?
var obj = { toString: 123 };
var s = obj.toString(); // fails
var s = '' + obj; // also fails, btw
Solution?
var s = Object.prototype.toString.call(obj);
How do you tell if an object has a key?
var f = obj.hasOwnProperty('test');
Ooops. But wait. What if an object has a hasOwnProperty
key inside of it?
var obj = { hasOwnProperty: 123 };
var f = obj.hasOwnProperty('test'); // fails
Solution?
var f = Object.prototype.hasOwnProperty.call(obj, 'test');
How do you loop around all the keys in an object?
for (var key in obj)
console.log(key);
Ooops. But wait. What if someone adds something to Object.prototype
?
Object.prototype.foo = 1;
for (var key in obj)
console.log(key); // now includes 'foo'!
Solution?
for (var key in obj){
if (!obj.hasOwnProperty(key))
continue;
console.log(key);
}
Ooops again! Can't use hasOwnProperty
directly like that... let's try again...
for (var key in obj){
if (!Object.prototype.hasOwnProperty.call(obj, key))
continue;
console.log(key);
}
There you go!