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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With