Reputation: 99959
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);
Upvotes: 2
Views: 1433
Reputation: 2476
Primitive values don't have accessible prototypes.
var foo = "hello",
bar = false;
foo.prototype; // undefined
bar.prototype; // undefined
For primitive values you have
More information can be found on https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Upvotes: 6
Reputation: 21759
your var foo
is a primitive object, so you wont be able to access its prototype, if you check the following link:
You get an example of exactly what you are doing, and says it will throw an TypeError
like you got
As per the docs, you can do as follows:
var proto = {}; var obj = Object.create(proto); Object.getPrototypeOf(obj) === proto; // true
But I dont see any reference where you can call Object.getPrototypeOf
from a string.
So you should create a new String object:
var foo = new String('baz');
Upvotes: 1
Reputation: 57709
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
.
Upvotes: 4