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 { … }.

share|improve this question
5  
Um. Because they're different languages? – Ryan Kinal Dec 22 '11 at 18:33
new is used in Javascript too. {} is a generic object, not an instance of a class. It's like new stdclass() in PHP. – NickC Dec 22 '11 at 21:47
why negative votes...? – nuthan Dec 23 '11 at 6:46
feedback

3 Answers

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.

share|improve this answer
feedback

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.

share|improve this answer
Well, the code a = { x: 'foo' } could be syntactic sugar for the Java code: a = new HashMap<String, Object>; a.put("x", "foo");. It just wouldn't be a very good feature, as it would encourage the use of HashMaps of Objects. – JGWeissman Dec 22 '11 at 22:43
feedback

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

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.