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:
var dentist = { 'first-name' : 'Sajjadul', 'last-name' : 'Robin', 'age' : 30 };
Retrieval:
dentist['first-name'] ;// Sajjadul
If key is legal Javascript name and not reserved word, ‘.’ notation can be used.
dentist.age; // 30
If a key does not exist, trying to access that key will produce undefined.
Trying to access value from undefined produces TypeError exception.
Reference:
Objects are always passed by reference. It is never copied.
var anotherDentist = dentist; anotherDentist.experience = '5year'; dentist.experience; // 5 year
anotherDentist and dentist refers to same object.
#Creating new Object:
It’s better to use create function instead of using new for creating new object. If create function does not exist for Object, the following can be used:
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 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 will remove
1. Property from All Object if objects are created with assignment (pass by reference)
2. Property from current Object if Object is created with create function.
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 here:
The post Javascript – The Good Parts: Object appeared first on Learn from mistake.