It's not the setup to a joke, i'm really asking.
Douglas Crockford is fond of saying that in the javascript prototypal object-oriented language there is no need for new
.
He explains that new
was simply added to give people coming from class-based (i.e. "classical") object oriented programming languages some level of comfort:
JavaScript, We Hardly
new
YaJavaScript is a prototypal language, but it has a
new
operator that tries to make it look sort of like a classical language. That tends to confuse programmers, leading to some problematic programming patterns.You never need to use
new Object()
in JavaScript. Use the object literal{}
instead.
Okay, fine:
new
bad{}
good
But then commenter Vítor De Araújo pointed out that the two are not the same. He gives an example showing that a string
is not like an object
:
A string object and a string value are not the same thing:
js> p = "Foo" Foo js> p.weight = 42 42 js> p.weight // Returns undefined js> q = new String("Foo") Foo js> q.weight = 42 42 js> q.weight 42
The string value cannot have new properties. The same thing is valid for other types.
What is going on here that an string
is not an object
? Am i confusing javascript with some other languages, where everything is an object?