Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Object.getPrototypeOf

I am trying to set the prototype of an object.

However, sometimes I want to set/get the prototype of a string. Surprisingly, however, I get an error when I call:

var foo = 'baz';
Object.getPrototypeOf(foo);

It throws:

TypeError: Object.getPrototypeOf called on non-object
    at Function.getPrototypeOf (native)

Why is that, and how can I get around it?

I want to be to able to set and get the prototype of a string. The one weird thing is that I can do this without an error:

var myProto = {};

var foo = 'baz';
Object.setPrototypeOf(foo,myProto);
like image 973
Alexander Mills Avatar asked Apr 26 '26 07:04

Alexander Mills


2 Answers

Primitive values don't have accessible prototypes.

var foo = "hello",
    bar = false;

foo.prototype; // undefined
bar.prototype; // undefined

For primitive values you have

  • Null
  • Boolean
  • String
  • Number
  • Undefined
  • Symbol (hello es6)

More information can be found on https://developer.mozilla.org/en-US/docs/Glossary/Primitive

like image 54
Afonso Matos Avatar answered Apr 28 '26 21:04

Afonso Matos


In JavaScript there are 7 datatypes: 6 primitive types and objects. The primitive types are Boolean, Null, Undefined, Number, String and Symbol.

var foo = 'baz';

Creates a primitive type String 'baz'.

var foo = new String('baz');
Object.getPrototypeOf(foo); // String

Creates an object of type String.

like image 21
Halcyon Avatar answered Apr 28 '26 19:04

Halcyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!