After Javascript: Grammar now it’s time for Object. Simple types of JavaScript are
- Numbers
- Strings
- Booleans
- null
- Undefined
- All others are Objects
Simple Object:
1 2 3 4 5 6 7 | var dentist = { 'first-name' : 'Sajjadul', 'last-name' : 'Robin', 'age' : 30 }; |
Retrieval:
1 2 3 | dentist['first-name'] ;// Sajjadul |
If a key is legal Javascript name and not reserved word, ‘.’ notation can be used. Click To Tweet
1 2 3 | dentist.age; // 30 |
If a key does not exist, trying to access that key will produce undefined.
Trying to access a value from undefined produces TypeError exception.
Reference:
Objects are always passed by reference in javascript. It is never copied. Click To Tweet1 2 3 4 5 | var anotherDentist = dentist; anotherDentist.experience = '5year'; dentist.experience; // 5 year |
#Creating a new Object:
It’s better to create a function instead of using new for creating a new object. If function creation does not exist for Object, the following can be used:
1 2 3 4 5 6 7 8 9 | if(typeof Object.create != 'function'){ Object.create = function(o){ var F = function(){}; F.prototype = o; return new F(); } } |
If Object.create() is used instead of assignment for creating a new Object, then prototype has no effect on updating.
hasOwnProperty: This method to check if an object has a particular property
Delete: Deleting a property from Object may remove
1. Property from All Object if objects are created with an assignment (pass by reference)
2. Property from current Object if Object is created with create function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var dentist = { 'name': 'Robin', 'age' : 30 }; var anotherDentist = dentist; anotherDentist.age = 10; document.write(dentist.age); //10 delete anotherDentist.age; document.write(anotherDentist.age); //undefined anotherDentist = Object.create(dentist); anotherDentist.age = 50; delete anotherDentist.age; document.write(dentist.age); //undefined |
Like to know more about Good Parts of Javascript, subscribe