canjs / can-util

Essential utilities used by lots of CanJS's projects.
https://canjs.com/doc/can-util.html
MIT License
10 stars 8 forks source link

A smarter `isPlainObject`? #300

Open justinbmeyer opened 7 years ago

justinbmeyer commented 7 years ago

Looking at our jQuery-like solution to isPlainObject and https://github.com/jonschlinkert/is-plain-object/blob/master/index.js

I'm wonder if an easy check might just be:

isPlainObject = function(obj){
  return Object.prototype.toString.call(o) === '[object Object]' && Object.getPrototypeOf(obj) === Object.prototype;
}

I suppose this won't work cross realm.

justinbmeyer commented 7 years ago

This solution (https://github.com/jonschlinkert/is-plain-object/blob/master/index.js ) basically checks if the prototype has the same shape as the Object.prototype.

This is very similar to can-reflect's isConstructor test, which over the function's prototype and checks that it looks like a "base" function's prototype.

Of course, this might mean it fails for Object.create(null).

justinbmeyer commented 7 years ago

Lodash's version of this is pretty smart. I used an idea from it in can-reflect. After 3.9, I'm going to point can-util at using can-reflect's version of this.