-2

I have just thought about creating new objects in javascript. I've read, that in JS every object creation is dynamic.This means that you can create an object and after that you can add some properties inside.But fields, which were created in constructor, are dynamic too.

I know that in a lot of other languages we have object structure and you can't add something to object after creation.So the question is, why fields, which are written in constructor, are dynamic created?

  • Because javascript is dynamic and can be manipulated in the browser console by the client... hence it being a client-side language. – NewToJS Aug 27 '15 at 08:08
  • Have a good read at: http://stackoverflow.com/questions/186244/what-does-it-mean-that-javascript-is-a-prototype-based-language – Marvin Smit Aug 27 '15 at 08:08
  • In fact at least in Java you can add/modify properties or method via reflection. – px5x2 Aug 27 '15 at 08:14

1 Answers1

0

It's a language design philosophy.

Some languages are designed to make it easy for the compiler to check that all structure and class accesses are correct. They require all the members to be declared ahead of time, and you can't change the structure of objects. This makes programs less flexible, but catches many types of errors when compiling. C and C++ are like this.

Other languages are designed with flexibility in mind, as well as allowing incremental development in an interpreter. They use dynamic data structures for objects, and allow you to define new methods at run time. The cost paid for this flexibility is that some errors that could have been detected by the compiler in C-style languages can only be detected when you run the program (and some of them may even go undetected). Javascript and Lisp are examples of this.

And some languages are somewhere in between. PHP allows you to add properties to classes, but I don't think you can add methods on the fly.

Barmar
  • 741,623
  • 53
  • 500
  • 612