12/08/2018, 13:09

[Fundamental] Insights Javascript Object

I can bet that all of us have already known about Javascript and at least one time we heard about Object of Javascript. However, how much do we know about Object ? I don’t think my post bellow contains adequate information about it but I can guarantee that you will never miss any basic ...

I can bet that all of us have already known about Javascript and at least one time we heard about Object of Javascript. However, how much do we know about Object ? I don’t think my post bellow contains adequate information about it but I can guarantee that you will never miss any basic concept about Javascript Object

Javascript is an Object Oriented Programming (OOP) language, so basically, we can wrap up everything in Javascript in single word: Object. I don’t want to express Object in a academic way that can be fit with any data types such as String or Array, in Javascript it’s simply pairs of unique keys that correspond to a value => we call this pair a property.

For example: I got a Honda motobike and here is my hondaBike feature

Property Value
name Future
capacity 125cc
color Red

However, I need to create the hondaBike with empty properties by:

var hondaBike = Object.create(null);

We’ve already had an object but it contains no properties, therefore we should add more properties to make a portrait about hondaBike

Properties in JavaScript are dynamic. That means that they can be created or removed at any time. Properties are also unique, in the sense that a property key inside an object correspond to exactly one value.

Javascript properties can be made by Object.defineProperty function which takes reference to an specific object, the name of property to create and descriptor that defines the semantics of the property

Object.defineProperty(hondaBike, 'name', {value: 'Future', writable: true, configurable: true, enumerable: true});

Object.defineProperty(hondaBike, 'capacity', {value: '125cc', writable: true, configurable: true, enumerable: true});

Object.defineProperty(hondaBike, 'color', {value: 'red', writable: true, configurable: true, enumerable: true});

Object.defineProperty will create a new property if a property with the given key does not exist in the object, otherwise it'll update the semantics and value of the existing property.

Alternatives

We have a short cut to define many properties of object through Object.defineProperties

Object.defineProperties(hondaBike,
{name: {value: 'Future', writable: true, configurable: true, enumerable: true}},
{capacity: {value: '125cc', writable: true, configurable: true, enumerable: true}},
{color: {value: 'red', writable: true, configurable: true, enumerable: true}});

Obviously, both two above calls are overtly verbose — albeit also quite configurable —, thus not really meant for end-user code. It’s better to create an abstraction layer on top of them

I think many of you have questioned about value , configurable and writable. All of them belong to descriptors which carry the semantics of a property. Descriptors can be classified into two main types: data descriptors and accessor descriptors

However, both two types of descriptors contain flags that define how a property is tread in particular context.

Now, let’s move on each of descriptors :

  • writable : handle ability to change concrete value of property. Applying to data descriptors

  • configurable : handle ability to change type of property or remove it

  • enumerable : handle ability to list property in a loop through properties of the objects

  • value : contain value of a property

  • get() : a function called with no arguments when the property value is requested

  • set() : a function called with the new value of property when user tries to modify the value of property

From above parts, we can create the object with some properties, however, it seems we’re have to care to much information when working with Object. That’s why Javascript provide another way for working with properties which can make Object to be a good friends for programmers.

4.1 Bracket notation

<identifier>"["<expression>"]"

Generally, identifier is the variable that holds the object containing the properties that we want to access and expression is the name of that property. There are no constraints in which name a property can have. So we can do #2 part in a simple way

hondaBike['name'] = 'Future';
hondaBike['capacity'] = '125cc';
hondaBike['color'] = 'Red';

4.1 Dot notation

<identifier>"."<identifier-name>

This is an alternative to refer a property besides of Bracket Notation. Fairy to compare, it’s much more easier than Bracket Notation however, it only works when the property name is a valid Javascript Identifier Name which’s meaning that we cannot access a property start with number by Dot Notation and we have to comeback to bracket notation

hondaBike['@hanoi'] = true; //valid
hondaBike.@hanoi = true; //Type Error, invalid

Both of these syntaxes are used for creating a data property with all semantic flags set to true .

Retrieving the values stored in a given property is as easy as creating new ones, and the syntax is mostly similar as well — the only difference being there isn't an assignment. So, if we want to know value of hondaBike's name:

hondaBike['name']
//=> 'Future'

If the case that property doesn't exist in object, it will return undefined

hondaBike['owner']
//=> undefined

To remove entire properties from an object, JavaScript provides the delete operator. So, if you wanted to remove the color property from the hondaBike object:

 delete hondaBike['color']
 //=> true

 hondaBike['color']
 //=> undefined

Then now the color property has gone

When reading the descriptors part, I'm sure that many of you questioned about set and get. Therefore, I'll explain more in this part Basically, both set and get allow us to read or set property value, especially defining how to handle each situation.

Firstly, let define some properties for hondaBike

Object.defineProperty(hondaBike, 'capacity', { value: 125, writable: true })
Object.defineProperty(mikhail, 'unit', { value: 'cc', writable: true })

We can define a common way to access and set both value at the same time named cylinder

function get_cylinder() {
  return this.capacity.toString() + ' ' + this.unit;
}

function set_cylinder(newVal) {
  var cylinder = newVal.trim().split(/s+/);
  this.capacity = cylinder['0'] || ';
  this.unit = cylinder['1'] || ';
}

Object.defineProperty(hondaBike, 'cylinder', {get: get_cylinder, set: set_cylinder, configurable: true, enumerable: true});

Cooking part is done, now let try the taste

hondaBike.cylinder = "125 cc"
//=> "125 cc"
hondaBike.capacity
//=> "125"
hondaBike.unit
//=> "cc"

Of course, using getters and setters will slow down process of accessing and modification. So, it's much better if we use the traditional way

I guess that so many guys will use Object.keys for listing object properties however, it's for properties having enumerable

Object.keys(hondaBike)
//=> ['name', 'cylinder', 'color']

If you want to retrieve all properties, calling Object.getOwnPropertyNames will satisfy you

Object.getOwnPropertyNames(hondaBike)
//=> ['name', 'cylinder', 'color', 'capacity', 'unit']

I've worked with Javascript for over 2 years but the main concept about object is just a data type which similar to Hash in Ruby. However, after researching about it, I found that it was much more interesting. I hope that all of you will have a comprehensive view about Javascript Object when reading this post.

0