Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How JavaScript programs bring dynamic behaviour with Reflective Functionality

The article’s objective was to make the readers aware on the benefits of reflective functionality that JavaScript brings in to the programs.

Introduction

Reflection is one of the greatest feature that Java language has introduced in itself that possess the potential to offer a technique for a Java class to inspect it of its own. It also assists in manipulating its member attributes and methods. With the use of reflection, Java class can query another class for the names of all its members and then exhibit or display them. Before the introduction of Java, there was no programming language that could make it possible to examine and manipulate a Java class from within itself. It is only after the introduction of Java that other languages such as PHP and .NET have also initiated to implemented their own Reflection APIs. Here is this article we are going to see the ability of JavaScript to offer reflective feature.

A look at the Reflection Uses

There is no way sometimes we foresee of knowing what you'd like to do until and unless you reach to that point. In such case, it is really beneficial to query an object and then fetch an interface of its attributes as well as services.

Let us think of the way as ordering from a menu. Conventionally, the use of the reflection was to load a module that

  • are listed an assembly manifest or XML file,
  • locate a class from this assembly, and
  • Create an instance of it.

Such a process or procedure would take lot of lines of code in the absence of reflection. The process could also be deployed in order to verify for public property access modifiers.

The below code reflects the list of methods in the form model with the help of each field's public getter accessor:

//create the reflection class
$cls = new ReflectionClass('NewsPost');
//use reflection to get all the NewPost class's methods
$methods = $cls->getMethods();

//loop through the methods and set the field names based on
//the getters - aka, get[FieldName]
$fields = array();
foreach($methods as $method) {
  if(substr($method->getName(), 0, 3) == 'get') {
    //Just take everything after get as the field name
    $fields[] = substr($method->getName(), 3);
  }
}

Making use of the above field names, we can then utilize it to create a form with minimal amount of HTML coding:

<?php foreach($fields as $field): ?>
  <p>
    <label for="<?php echo $field; ?>"><?php echo $field; ?></label>
    <input type="text" name="<?php echo $field; ?>" id="<?php echo $field; ?>" />
  </p>
<?php endforeach; ?>

Let us see how reflection provides dynamic property to the programs.

Retrieving Object's Public Attributes

If you notice carefully, here we have used the terms class and object interchangeably. The fundamental difference that is known to everyone about Java and JavaScript that Java is made up of classes and on the other hand JavaScript is made up of objects, however there are no classes as such.

When trying to emulate a Java attribute, it assists us to think of a JavaScript object as a class of sorts. However, it does not add of its own all the natural traits of true Object-Oriented classes. This comprises of encapsulation. The below lists the JavaScript object that could be referred as the Person class: There are two private attributes namely getter and setter, two public properties, as well as two public methods:

var Person = function() { 
    //defaults
    var _age  =  0,
        _name = 'Steve Smith';

    this.initialize = function(name, age) {
      _name = _name || name;
      _age  = _age  || age;
    };
    
    if (arguments.length) this.init();
    
    //public properties. no accessors required
    this.phoneNumber = '777-224-3333';
    this.address     = '33 Acacia ave. New York, USA';
    
    //getters and setters
    this.getName     = function()      { return _name; };
    this.setName     = function (name) { _name = name; };
    
    //public methods
    this.addBirthday = function()      { _age++; };
    this.toString    = function()      { return 'My name is "+_name+" and I am "_age+" years old.'; };
}; 

//create an instance of a person
var bob = new Person('Bob', 33); //still 33! (I desire!)

The Reflector class takes a class instance as constructor argument and you cannot make use of the Person class template for the reason that it does not comprise of any attributes or properties. This is for the reason that it's a function and not an object. Post this, the Reflector's methods can be called, or rather, method at this point.

var Reflector = function(obj) {
  this.getProperties = function() {
    var properties = [];
    for (var prop in obj) {
      if (typeof obj[prop] != 'function') {
        properties.push(prop);
      }
    }
    return properties;
  };
}

var reflector = new Reflector(rob);
document.write('<p>Person class properties:</p>');
document.write(reflector.getProperties().join('<br/>'));

The following is produced by the above code:

Person class properties:
phoneNumber
address

Retrieving all the Public Methods of a Class

With the help of "all methods", we have introduced or incorporated over here the overridden methods and also the Person class's own methods. This process is much on the similar lines of the earlier one with the exception that the expectation now is to get the members who's type is "function":

this.getAllMethods = function() {
  var methods = [];
  for (var method in obj) {
    if (typeof obj[method] == 'function') {
      methods.push(method);
    }
  }
  return methods;
};

//...
document.write('<p>Public Methods:</p>');
document.write(reflector.getAllMethods().join('<br/>'));

The below displays the outcome:

Public Methods:
initialize
getName
setName
addBirthday 
toString

Getting an Object's Own Public Properties

The OwnProperty() method possess by the object gives back the true value in the case when a method was created by the object which houses it. Also this is not overridden from the previous or earlier one. And when we include all this in the if statement, it will get rid of all the inherited methods:

this.getOwnMethods = function() {
  var methods = [];
  for (var method in obj) {
    if (  typeof obj[method] == 'function'
       && obj.hasOwnProperty(method)) {
      methods.push(method);
    }
  }
  return methods;
};


//...
document.write('<p>Own Public Methods:</p>');
document.write(reflector.getOwnMethods().join('<br/>'));

Now, if you see, the overridden toString() method is not present in the list:

Own Public Methods:
initialize
getName
setName
addBirthday

Hope you liked the article, see you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login