Is String an instance of a String () object?

I am currently studying javascript, and there is something that I do not understand.

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

So, if I use ("ThisIsMyString" instanceof String), I would have to return true, right? But it turns out that it returns false .. and I believe that this is because of the primitive type.

Here is my question: if "ThisIsMyString" is not an instance of String, how can it access the property from this object? What part of the riddle that I do not know?

+6
source share
3 answers

String.length is not

method from String.prototype

length - property strings

See MDN docs for String.length


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

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

However, as your string literal has access to these methods / properties

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

If you need an actual String instance

 var str = new String("hello"); str instanceof String // true 
+1
source

You can use such methods because the language recognizes and converts the primitive type to a temporary instance of the String object and returns the length property of this object.

0
source

Adapted from http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html : "JavaScript implicitly wraps a string primitive in a String object, processes the property of a String object or method call, and then deletes the object"

Read more below.

0
source

Source: https://habr.com/ru/post/957956/


All Articles