I code in PHP and JavaScript. Why do the two languages use a different syntax for creating objects, classes, functions, even if they are both OO? For example, in PHP, we use the new
keyword to create an object, but in javascript it is { … }
.
|
||||
Well there are a few factors. First of all its just a matter of syntax. Javascript provides an object literal syntax (which to be honest I wish PHP had) But more importantly PHP uses class based objects, while JavaScript uses a prototype based object system, in which there are no classes but each object is a desendent of an other object. |
|||
|
The "{}" notation vs "new" notation isn't where the difference is. Remember that "var a = { x: 'foo' }" is equal to "var a = new Object(); a.x = 'foo';". The real difference is that the {} notation allows you to create a weak type, an object that has a "shape" that is determined on-the-fly, without there being a class definition. Java's strict typing makes it impossible to have the {} notation there. |
|||
|
The fundamental difference between JavaScript and Java is: There are no classes in JavaScript. This gives you great flexibility, as you dont need a class "blueprint" when creating a new object. this is a very open question: for more information on the topic, visit Eloquent JavaScript, Chapter 4 |
|||
|
Its been such a long time, I wasn't convinced from the answers above. To a certain extent, the answer at stack-overflow is sensible http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work#4778408 |
|||
|
new
is used in Javascript too.{}
is a generic object, not an instance of a class. It's likenew stdclass()
in PHP. – NickC Dec 22 '11 at 21:47