Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String an instance of the object String()? [duplicate]

Tags:

javascript

I am currently learning javascript and there is something that I don't understand.

//This means that I am using a method from the String.prototype
"ThisIsMyString".length

So, if I use ("ThisIsMyString" instanceof String) was suppose to return true, wasn't it? But turns out that returns false.. and I belive that is because the primitive type.

Here is my question: If "ThisIsMyString" is not an instance of String, how it can access property from that Object? What's the part of the puzzle that I don't know?

like image 350
Rodrigo Pereira Avatar asked Nov 12 '13 22:11

Rodrigo Pereira


1 Answers

String.length is not

a method from the String.prototype

length is a property of String

See the MDN docs for String.length


To answer your question though, the reason "hello" instanceof String returns false lies within how instanceof actualy works

Object.getPrototypeOf("hello")
// TypeError: Object.getPrototypeOf called on non-object

However, this is how your string literal has access to these methods/properties

"my string".constructor === String
// true

"my string".__proto__ === String.prototype
// true

If you want an actual instance of String

var str = new String("hello");
str instanceof String
// true
like image 70
maček Avatar answered Nov 05 '22 10:11

maček