In javascript everything is object. A very clear idea of object structure is needed to understand the subject well…
- if you go to MDN you will find some built in objects like arrays, document, date, evalError etc. If you alert any object, it will simply call the object’s toString method. We can override default toString method.
- Important: “this” keyword. To access any objects property, we use ‘this’.
var person = { name: "sajib", age: 34, toString: function(){ return this.name; } }; alert(person); alert(person.age); - another way to create object, note that here we have to use ( ) around { }
var person = new Object({ name: "sajib", age: 34, isAdult: function(){ return this.age > 18 ? true : false; } }); alert(person.isAdult()); - Mostly used way of constructing object is to use constructor function. It is simillar to class of other languages.
function person(name, surname, age){ this.name = name; this.surname = surname; this.age = age; this.isAdult = function(){ return this.age > 18 ? true : false; }; } var sajib = new person("sajib", "biswas", 34); var mamun = new person("mamun", "jamal", 35); alert(sajib.isAdult()); // this will add a new property to all objects. i.e. .prototype adds property to class person.prototype.experience = 5; alert(sajib.experience); alert(mamun.experience);
Leave a Reply