Note that there are some explanatory texts on larger screens.

plurals
  1. POHow is a Javascript string not an object?
    text
    copied!<p><em>It's not the setup to a joke, i'm really asking.</em></p> <p><a href="http://www.yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/" rel="noreferrer">Douglas Crockford is fond of saying</a> that in the javascript prototypal object-oriented language there is no need for <code>new</code>. </p> <p>He explains that <code>new</code> was simply added to give people coming from class-based (i.e. "<em>classical</em>") object oriented programming languages some level of comfort:</p> <blockquote> <h1><a href="http://www.yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/" rel="noreferrer">JavaScript, We Hardly <code>new</code> Ya</a></h1> <p>JavaScript is a prototypal language, but it has a <code>new</code> operator that tries to make it look sort of like a classical language. That tends to confuse programmers, leading to some problematic programming patterns.</p> <p>You never need to use <code>new Object()</code> in JavaScript. Use the object literal <code>{}</code> instead. </p> </blockquote> <p>Okay, fine: </p> <ul> <li><code>new</code> bad </li> <li><code>{}</code> good</li> </ul> <p>But then commenter <a href="http://www.yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/#comment-588504" rel="noreferrer">Vítor De Araújo pointed out that the two are not the same</a>. He gives an example showing that a <code>string</code> is not like an <code>object</code>:</p> <blockquote> <p>A string object and a string value are not the same thing:</p> <pre><code>js&gt; p = "Foo" Foo js&gt; p.weight = 42 42 js&gt; p.weight // Returns undefined js&gt; q = new String("Foo") Foo js&gt; q.weight = 42 42 js&gt; q.weight 42 </code></pre> <p>The string value cannot have new properties. The same thing is valid for other types.</p> </blockquote> <p>What is going on here that an <code>string</code> is not an <code>object</code>? Am i confusing javascript with some other languages, where everything is an object?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload