Dynamic Access

To access a field, a property, or a method, we use the dot notation in JavaScript much like in languages like Java, C#, and many other languages. However, in addition, we can access a member of an instance using the [] operator—we’ll look at yet another alternative to this in Getting and Setting Properties.

Use the dot notation, like sam.age or sam.play(), if you know the member name at code writing time. If the member name is not known until runtime, then use the [] notation. Suppose variables named fieldName and methodName contain the name of a field and a method—for example, "age" and "play", respectively. Then sam[fieldName] is equivalent to writing sam.age and sam[methodName]() is like writing sam.play().

If you’re curious to find all the members in an instance named instance, use the Object.keys(instance) method. The reason the method is called keys is that JavaScript considers objects to be like hashmaps, with keys and values. Alternatively, you can iterate over the members using the for member in instance {} form. Let’s try out these facilities with an example.

 class​ Person {
 constructor​(age) {
 this​.age = age;
  }
 
  play() { console.log(​`The ​${​this​.age}​ year old is playing`​); }
 
 get​ years() { ​return​ ​this​.age; }
 }
 
 const​ sam = ​new​ Person(2);
 
 console.log(sam.age);
 sam.play();
 
 const​ fieldName = ​'age'​;
 const​ methodName = ​'play'​;
 
 console.log(sam[fieldName]);
 sam[methodName]();
 
 console.log(​`Members of sam: ​${Object.keys(sam)}​`​);
 
 for​(​const​ property ​in​ sam) {
  console.log(​`Property: ​${property}​ value: ​${sam[property]}​`​);
 }

We access the field and the method using both the dot notation and the [] notation. We also query for the keys and iterate over the keys. Let’s take a look at the output:

 2
 The 2 year old is playing
 2
 The 2 year old is playing
 Members of sam: age
 Property: age value: 2

The code behaved as expected for the most part. While the age field showed up in the keys and the iteration of keys, the constructor, the play() method, and the years property went AWOL. That’s because these are not directly part of the object but are kept in the object’s prototype. Let’s query the prototype using the getOwnPropertyName() method of Object, like so:

 console.log(Object.getOwnPropertyNames(Reflect.getPrototypeOf(sam)));

The getOwnPropertyName() method gets the properties and fields of a given object. The constructor, the properties, and the methods defined in a class are stored as properties in its prototype. Let’s examine the output of this last code snippet to see evidence of this:

 [ 'constructor', 'play', 'years' ]

With the ability to dynamically access members and to iterate over the keys, we can explore any object at runtime, much like how we use reflection in languages like Java and C#.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset