最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js - Object.getPrototypeOf - Stack Overflow

programmeradmin4浏览0评论

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);

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);
Share Improve this question edited Jun 8, 2015 at 21:13 Alexander Mills asked Jun 8, 2015 at 20:59 Alexander MillsAlexander Mills 101k166 gold badges537 silver badges918 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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/en-US/docs/Glossary/Primitive

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.

your var foo is a primitive object, so you wont be able to access its prototype, if you check the following link:

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf

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');
发布评论

评论列表(0)

  1. 暂无评论