简体   繁体   中英

Why does MDN say “everything is an object in JavaScript”?

On an MDN page about string methods ( https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods ), it says "We've said it before, and we'll say it again — everything is an object in JavaScript." But another MDN page states there are 7 data types in JavaScript, 6 primitives and object ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types ). This is simply a mistake, correct? Or is there something I'm missing?

My terminology may be off, and I'm not one to pay attention to details like these, but maybe this helps clarify it a bit.

For example, number variables have the toExponential method. Eg, this is invalid 3.toExponential(2) , but this is totally valid let a = 3; a.toExponential(2); let a = 3; a.toExponential(2); . On the other hand, both typeof 3 and typeof a returns the string 'number' .

So there's a distinction between what's an 'object' (roughly, what can have methods) and the data type a variable or literal can reference.

I think it is a poor choice of phrasing. Things that are passed by reference are objects (array, or plain object, functions etc). The primitive data types are passed by value and I would consider null to be a keyword (it is also an object). The correct phrase would be:

"Everything can be represented as an object"

This would clear the misconception, as others pointed out, the only way you can call functions from Number.prototype or String.prototype is for the engine to implicity wrap the primitive as an object. The same way, you can do this (function(){console.log(this)}).call(5) //Number {5}

every data type is instance of it's own class. like for example string. any string is instance of Class String all instance inherits methods from String class. methods are available only to object so you can consider that string is object to. but for sake continence all datatypes exists..

i tried to explain the concept but it's complicated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM