About

Labels

slider

Recent

Navigation

Object in Javascript explained


I've been through this in one of my previous post. But this one is going to be a detailed over what Javascript object and prototype works in real browser. Each and every object holds two basic things: methods and properties. Now what is a difference between properties of an object and normal Javascript variables and what is the difference between methods and normal Javascript function? Well, you find them in detail within this post.

Object

  1. The use of `new Object()` is older try using {} instead.
  2. Do not confuse it with jQuery objects, those are auto generated objects and only accessible by jQuery methods therefore sometimes using them with native JS causes problems but not all of them, like length property.
  3. Objects are accessible via for...in loop in Javascript. This loop only iterates enumerable properties of an object.
  4. Defining an objects property using brackets [] is older method try using dot (.) syntax instead.
A basic example where dot syntax doesn't work but bracket syntax works is when property name is based on numbers and not the string.
Basically what makes a difference between native Javascript function and an object's method is the association. A function is independent of any object and can be triggered without associating with any object while a method is called with association with an object.
var myData={}; // An object

// Adding the method
myData.myName=function(e){
console.log("My name is "+e);
}
// Running the method
myData.myName('Hamza');

// A function
function myName(e){
console.log("My name is "+e);
}
// Running function
myName('Hamza Dhamiya');

// Logs
My name is Hamza
My name is Hamza Dhamiya
The same difference holds by the ordinary variable and object's property, that is association. However, the things are not that simple. A front end application can cause a big blunt in codes if object's method and properties are not used in correct way.

Assume a Javascript environment have many objects. Using of `this` keyword can cause the application to return wrong values or maybe `undefined` values while running a method. Because every page has window object which is the parent object present. Running a method outside the specific object will target window as a primary object. This misleading is not mention on many websites describing the Javascript's object oriented behavior. Therefore as above described condition we use call, bind and apply method.
var baby = {
name: 'Muhammad Ali',
age: '1 year'
}
// Creating a local baby object below
var hospital = {
baby: {
name: 'Saad',
age: '2 year'
},
getBaby: function(e) {
console.log('This is ' + this.baby.name + ' and he is ' + this.baby.age + ' old')
}
}
var currentBaby = hospital.getBaby;
currentBaby(); // This is Muhammad Ali and he is 1 year old
Above code example is from my one the post I wrote a few months back. This demonstrate how small errors could lead to a break down. The solution of this problem is to use other methods available, read them here.

Object property attributes 

Every object property contain its own attributes which actually changes our way of working with them. There are basically 3 kinds of attributes each data contain.

1. Enumerable

Okay now, this attribute is true for all defined properties but not the one inherited. Enumerable properties are those who iterate in for...in loop so if any property is set to non-enumerable then we won't see them in loop. Like length property is non-enumerable since it is inherited property.

To test the property we use obj.propertyIsEnumerable() that returns a Boolean. Like length or toSting() will return false while user defined properties will return true.
var car = {
name: 'Audi'
};
console.log(car.propertyIsEnumerable('toString')); // false
console.log(car.propertyIsEnumerable('name')); // true

2. Writable

All those properties which can be edited using JS syntax are known as writable. Once the object is said to non-writable then object's value is no longer changeable unless redefined using object.defineProperty()

3. Configurable

Those properties which can be deleted using `delete` syntax are simply configurable. If they are said to `false` using object.defineProperty() then they become non-configurable.

object.defineProperty()

This builtin method allows you to create an object's property by not only setting values but also setting the attributes which will define the working of the object.
var car={name:'Audi'}
Object.defineProperty(car,'model',{
value:'r8',
writable:false,
enumerable:true,
configurable:true
})
console.log(car.model) // r8
car.model='r10';
console.log(car.model) // r8
I am sure that you perhaps not aware by this method of changing the property's attribute. However it is quite a delighted method of working with objects.

Reference variable and property

Now reference of the variable to other variable might not be surprising if we working simple example like this one.
var car='Audi';
var updateCar=car;
car='Honda';
console.log(updateCar); // Audi
console.log(car); // Honda
After updating the variable the referenced variable didn't effect because it is the nature of variable however not the same nature is showed by the object property.
var car={myCar:'Audi'};
var updateCar=car;
car.myCar='Honda';
console.log(updateCar.myCar); // Honda
console.log(car.myCar); // Honda
As you can see updating the object's property also changes the referenced variable.

Objects in array

This is a common condition when objects are places in arrays. Consider an array contain more than 1 object. Now maybe all object have same properties and different values or maybe different properties. To get the value of the choice it necessary to handle to them using loops like we handle normal array.
var kids = [{
name: 'Ali',
age: '12'
}, {
name: 'Nasir',
age: '8'
}, {
name: 'Saad',
age: '5',
youngest: true
}];

function getKids(e) {
for (var i = 0; i < e.length; i++) {
var kid = e[i];
console.log(kid.name);
}
}

function getYoung(e) {
for (var i = 0; i < e.length; i++) {
var kid = e[i];
if (kid.youngest) {
console.log('Yougest Kid is:' + kid.name);
}
}
}
getKids(kids);
// Ali
// Nasir
// Saad
getYoung(kids);
// Saad
Well, the discussing over the use of jQuery's each method vs the use of `for` loop is worth discussing right here. If you ever thought of using the $.each method instead of `for` loop just for ease of coding then make sure that jQuery`s $.each method much more slower than `for` loop. The below image is taken from the stack overflow.
$().each vs $.each vs for loop in jQuery?
The reason is that jQuery $.each method is best for working with jQuery objects which I think the worst part of jQuery because the jQuery objects are too much slower in performance and each jQuery object creation takes time. Therefore Lea Verou's post must worth reading before using jQuery for big projects.

Stay connected for upcoming Javascript prototype post in this week for more about core concepts of JS.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: