Reputation: 508
The deeper I get into programming, the more old concepts I thought I knew confuse me. For example, the toString() method. How come I can apply this method to a variable thats not an object? Is it because toString() is a built in javascript method that can apply to all data types?
Upvotes: 1
Views: 63
Reputation: 539
You should learn about "prototypal inheritance". It is one of the most critical concepts of the javascript language to understand in my opinion.
The above answers are correct, but you aren't going to understand what they mean until you take some time to study this subject.
Hope that gives you some guidance!
Upvotes: 0
Reputation: 44105
Nearly everything is an object in JavaScript. What you would call primitives (strings, numbers, etc.) all have methods:
console.log("Message".toUpperCase());
console.log(123.toString());
So the reason you can apply toString
to anything - even if it doesn't seem like an object - is because everything is really a kind of object, which means it can have methods. Here's some examples of toString
on different things:
console.log(123..toString());
console.log(["A", "B", "C"].toString());
console.log(typeof true.toString());
Upvotes: 3
Reputation: 370789
There are multiple different kinds of toString
methods. There is Object.prototype.toString
, which any object will inherit. There is also Number.prototype.toString
, Boolean.prototype.toString
, and String.prototype.toString
.
When you do
'foo'.toString()
you're actually invoking String.prototype.toString
- you're not invoking Object.prototype.toString
.
Object.prototype.toString = () => 'changed';
console.log('foo'.toString());
Although strings and other things can be interpreted as objects, and have Object.prototype.toString
called on them, often you're just calling the primitive-specific method, like Boolean.prototype.toString
or String.prototype.toString
. (These prototypes do happen to inherit from Object.prototype
, but the Object.prototype.toString
method is shadowed over by the closer prototype method, and may well not even be considered)
Why do these methods exist for those primitives? Probably for the sake of consistency. If you have something that's not undefined
or null
, you'll know that you'll be able to call toString
on it.
Upvotes: 2