Javascript object and class
Published on: 20th July 2016
Updated on: 10th Jan 2022
Overview
You have three ways to declare a new object. The first way is to using a shorthand declaration while the second way is to declare a new object in the same way like other programming language.
var o = {};
o.name = 'Mike;
OR
var o = new Object();
o.name = 'Mike';
OR the latest way is to declare a new object type and then instantiate it.
class Customer
{
name;
}
var o = new Customer();
o.name = 'Mike';
Object usage
Unlike the strong typed programming language such as C# or C++, Javascript allows you adding new property at anytime regardless how you declared the object.
For example, adding name and age properties to an object instance:
o.name = 'John';
o.age = 18;
o.savings = 2100;
console.log(o);
You are allowed to remove any property at runtime:
delete o.savings;
console.log(o);
To retrieve all property names from an object, you need to call Object.keys()
function which returns an array of string:
var properties = Object.keys(o);
console.log(properties);
Let says, you want to access the property value without knowing the property name:
var age_of_the_person = o[properties[1]];
But, you can't access the property value by index:
var not_working = o[1];
console.log(not_working);
If you have instantiated an object from the class definition, then, you can check the class type with instanceof
keyword,
class Customer
{
name;
}
var o = new Customer();
o.name = 'Mike';
// output: true
console.log(o instanceof Customer);
The object type will not mutate even you added new field,
o.age = 18;
o.savings = 2100;
// output: true
console.log(o instanceof Customer);
Conclusion
The above explained the basics of an object and class keyword. The dynamic feature in JavaScript is very useful and it also causing lots trouble in debugging and testing the code. I will publish more on this topic in the future.
Jump to #JAVASCRIPT blog
Author
Lau Hon Wan, software developer.