I think that the dot operator can be apply to object only for access to his properties. I.e. for instance
var o={prop:'property'};
alert(o.prop);//property
When JS executing alert(o.prop);
first object which contains by reference o
will found further will be found property wich contains by reference o.prop
.
Let's write
simple='hello';
alert(simple.length);//5
I dont understand this. I'm excepted that in console will kind of error, because simple is no object.
String is an object inherent to JS. As such, it also has inherent properties, length being one of them. This property spits out the number of characters that are in a String object(as you've seen.)
If you wanted to you could override the inherent abilities of any inherent JS Object (String, Array, etc.) and create your own functionality, but that is generally a really bad idea.
In javascript,
everything is an object.length
andindexOf()
, etc)Checkout this list of objects JS has. Just because you can't see
{ }
does not mean that the variable is not an object. To get a list of properties of a data-type, you can write this in your console:
And depending on what your browser supports, you'll get this:
JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings.
So your
simple
var is a string instance, and it's inherits fromString.prototype
.Ref:
Quote from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
What's happening when you do something like
simple.length
is that, under-the-hood, the browser is temporarily convertingsimple
into an object of typeString
and then looking uplength
on that. It's almost like callingnew String(simple)
except the browser doesn't actually need to create a new object, it just needs to behave as if it did. One thing to note is that this is all temporary:Actually, it is a
String
object. JS implicitly converts the primitive string type to aString
object when you apply string methods to it.It's wrong to say that "everything is an object" in JavaScript because there are primitive types that are not objects, including a string primitive. In many cases the implicit conversion between primitives and objects can easily obscure the fact.