2

I need a way to detect if prototype is built in JavaScript object (default prototype) as Object, Array, Date, Function etc.. Or is it custom user defined object.

Consider following code

const a = { a: 1 };
const b = Object.create(a);

const aProto = Object.getPrototypeOf(a); // Default prototype
const bProto = Object.getPrototypeOf(b); // User defined prototype

// One way to detect it would be 
aProto === Object.prototype; // [true] we know it's default object
bProto === Object.prototype; // [false]

Above check would require to test for Array.prototype, Function.prototype, Date.prototype, etc...

Is there smarter way to achieve this?

Added

Context of what I'm trying to achieve. I want to modify object properties then I want to go over his prototype chain and do the same for objects on his prototype up until I reach the built in object that I want to skip without modifying.

In example from above I would modify all properties of object b then I would go to his prototype which is object a and modify all of his properties. Then I would go to prototype of a which is now built in object. I would like to detect that a have built in object as prototype and skip modifications.

snovakovic
  • 314
  • 1
  • 8
  • 2
    https://davidwalsh.name/detect-native-function – gurvinder372 Oct 17 '17 at 13:57
  • Possible duplicate of [Detect if function is native to browser](https://stackoverflow.com/questions/6598945/detect-if-function-is-native-to-browser) – Liam Oct 17 '17 at 13:58
  • @gurvinder372 is `[native function]` being returned part of a spec? I only ask because I wonder if there is a more apt reason to need to detect if something is native or not. If there is, maybe there is a less brittle approach (I mean, if that way is even brittle). – zero298 Oct 17 '17 at 13:59
  • 1
    @zero298 Not sure, I can't find the same in the spec itself. – gurvinder372 Oct 17 '17 at 14:03
  • I need to detect if object prototype is one of built in objects prototypes. I don't need to test if function is native or not so I'm not able to use solutions from above. [built in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects). – snovakovic Oct 18 '17 at 07:39

0 Answers0