There are several ways to define a class in Javascript. I will be listing my favorite method below (JSON Method). It’s important to note that there are no real classes in JavaScript. Everything is considered an object. So below is our class definition:
1 2 3 4 5 6 7 8 9 10 |
<script> var Person = { age: "25", sex: "Male", location: "New York", getASL: function () { return 'Age: ' + this.age + ', Sex: ' + this.sex + ', Location: ' + this.location; } }; </script> |
So you can start using the class like this:
1 2 3 4 |
<script> Person.age = "29"; alert(Person.getASL()); <script> |
Actually thats an object. If you ever do new Person(), its ignored and your just copied the object. So what doesn’t work is if try to prototype Person so what every existing object of Person will also be extended with the new function / variable.
so it should be:
or
Its an anal comment but still something nice to know.
and how does one define a function with input? How would one, for instance, define a setAge(var age) function for Person, so we can say
This was very helpful.
If you interested on JSON style JavaScript class declaration talks in more detail…
http://mahtonu.wordpress.com/2010/04/13/json-style-javascript-object-declaration/
Nice post 🙂
Actually JSON objects are singleton objects by design, not by choice, since they have no constructor. I really like JSON 😀
So using the JSON you can define a class, while at the same time creating an instance (object) of that class, means that you can have only one single instance of this class at any time, you cannot instantiate more objects of the same class.
More here:
http://mahtonu.wordpress.com/2010/04/13/json-style-javascript-object-declaration/
Actually, Joseph Montanez, you never want to do (or suggest) what you’ve done in your first example.
You are redefining the prototype methods each and every time a new instance of the class is instantiated.
Have a look here:
http://ejohn.org/blog/simple-class-instantiation/
Incredibly beneficial article. I’ve discovered your web site by Google and I am genuinely happy about the information you present with your posts. Anyway keep in the great hard work!