BonsaiDen / JavaScript-Garden

A collection of documentation about the most quirky parts of the JavaScript language.
http://bonsaiden.github.com/JavaScript-Garden
MIT License
3.45k stars 557 forks source link

Explain the difference between objects and primitives #55

Closed DmitryBaranovskiy closed 10 years ago

DmitryBaranovskiy commented 13 years ago

For some reason you avoid this explanation, but I think, it’s a vital thing for understanding JS. Every time you use dot operator (or square brackets) JS trying to convert the thing on the left of operator to object. "string".length doesn’t make any sense, because string is not an object and can’t have properties, but JS actually does Object("string").length. The same way as "6" / 2 doesn’t make sense, but JS “replaces” it with Number(6) / 2.

Good example on understanding this difference: var a = 5; a.prop = "blah"; alert(a.prop); // undefined

That means that “Everything in JavaScript acts like an object…” is not correct. a doesn’t act like object here.

Kambfhase commented 13 years ago

Depending on how you specify proper acting of an object in JS your code might be expected behaviour. On the first line a is the number 5. On the second it is auto boxed via Number(5). That object gets the prop property set. On the next line however the reference to the box object is lost, so a is the primitive 5 again. Using property descriptors any object can act like the a above or we could cache the boxed a:

Object.defineProperty( Number.prototype, "prop", { set: function( val){ 
    window.target=this; 
    return val;
}});
var a = 5;
a.prop="blah";
a == target // true
a === target // false

Well, the point I am trying to make is that the difference between objects and primitives are quite blurry on the edges. I am not sure this belongs into the JS-Garden though. More like JS-HighSchool.

mfG Hase

DmitryBaranovskiy commented 13 years ago

I think it’s quite simple and important concept of JS to miss it out.

BonsaiDen commented 13 years ago

Hey Dmitry, feel free to write something up as I really don't have the time at the moment to do so. When you're done, just file a pull request that I can review :)

timruffles commented 10 years ago

@DmitryBaranovskiy any chance of that PR? Things are being merged now if you fancy it