Basic Object Creation


/ Published in: JavaScript
Save to your folder(s)

Create a simple object and add properties and a method. Note where the object is parsed (not from top to bottom).


Copy this code and paste it in your HTML
  1. function mooTutorial() {
  2. var city = { //create the city object
  3. numberOfCars : 0, //define number of cars property
  4. hasTraffic: true, //define if it has traffic
  5. grow: function(howMany) { //creates a grow() method. looks for variable howMany.
  6. this.numberOfCars += howMany; //adds howMany to numberOfCars.
  7. }
  8. }//This is where the object gets parsed, order of members is unimportant.
  9. console.info(city.numberOfCars); //outputs 0
  10. city.grow(10);
  11. console.info(city.numberOfCars); //outputs 10
  12. }
  13. window.onload = mooTutorial();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.