Skip to content

Instantly share code, notes, and snippets.

@velipso
Created December 3, 2016 05:36
Show Gist options
  • Save velipso/bb830a9558e74fb684fdcf300e589f9d to your computer and use it in GitHub Desktop.
Save velipso/bb830a9558e74fb684fdcf300e589f9d to your computer and use it in GitHub Desktop.
Short explanation on why JavaScript's object model sucks

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment