Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created November 25, 2014 22:04
Show Gist options
  • Select an option

  • Save WebReflection/87e41c09691edf9432da to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/87e41c09691edf9432da to your computer and use it in GitHub Desktop.
A cross platform JSON reviver able to return instances from namespaces
var protoReviver = (function (proto, hasNoProto) {
// (C) Andrea Giammarchi - WTFPL License
return function (k, v) {
if (k === proto && v !== null) {
for (var
tmp = window,
nmsp = v.split('.'),
i = 0;
i < nmsp.length;
i++
) {
tmp = tmp[nmsp[i]];
}
return typeof tmp === 'function' ?
tmp.prototype : tmp;
} else if (k === '' && v.hasOwnProperty(proto)) {
tmp = v[proto];
delete v[proto];
if (hasNoProto) {
tmp = Object.create(tmp);
for (k in v) {
if (v.hasOwnProperty(k)) {
tmp[k] = v[k];
}
}
v = tmp;
} else {
v.__proto__ = tmp;
}
}
return v;
};
}('__proto__', {__proto__:null} instanceof Object));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment