Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/9900019 to your computer and use it in GitHub Desktop.
Save WebReflection/9900019 to your computer and use it in GitHub Desktop.
if the only reason you like __proto__ is its literal integration, just use this and make the web better today. No credits needed
// ES5 dirty perf oriented tweet size
var O=function(O,s){s=O.setPrototypeOf||function(o,p){o.__proto__=p;return o};return function(p,o){return o?s(o,p):p||s({},p)}}(Object);
// ES5 dirty performance way
var O = function(Object){
var
create = Object.create,
set = Object.setPrototypeOf || function(o, p) {
o.__proto__ = p;
return o;
},
undefined
;
return function (p, o) {
return o === undefined ? (
p === null ? create(p) : p
) : set(o, p);
};
}(Object);
// ES5 full compliant way
var O = function(Object){
var
oProto = Object.prototype,
create = Object.create,
has = oProto.hasOwnProperty,
undefined
;
return function (p, o) {
var r, k;
if (o === undefined) {
o = p;
p = p === null ? p : oProto;
}
r = create(p);
for (k in o) {
if (has.call(o, k)) {
r[k] = o[k];
}
}
return r;
};
}(Object);
@WebReflection
Copy link
Author

examples

var n = O(null);
n instanceof Object; // false


var p = O(Array.prototype, {
  has: function (v) {
    return !!~this.indexOf(v);
  }
});

p instanceof Array; // true

var o = O({
  justObject: 1232
});

o instanceof Object; // true

var m = O(null, {
  my: 'dictionary'
});

m instanceof Object; // false
m.my; // dictionary

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