JavaScript: Reflection

JavaScript provides some rudimentary reflective abilities, or the ability for a computer to examine, identify, interpret, and potentially alter the structure of its code, state, and behavior at runtime. The heavy hitters in this arena are ‘typeof’ and ‘hasOwnProperty’.

Typeof allows a JS script to ask an object what its type is before it is acted upon. Due to JavaScript’s loosely typed structure, this ability can come in handy when it is possible that a function might receive a parameter that may be of the wrong type or of differing types and the cases need to be handled separately.

HasOwnProperty allows a JS script to ask an object if its supports a particular property. Properties can be both state properties as well as function properties.

'use strict';

// JavaScript Reflection
// Identifying the types of objects as well as whether or not objects have specific variables or functions
var person = {
    firstName: 'First name not provided',
    middleInitial: 'initial not provided',
    lastName: 'Last name not provided',
    age: 'Age not provided',
    sayYourName: function(){
        return "Hello, I am " + this.firstName + " " + this.lastName;
    }
};

//  1. Discovering the type of an Object using 'typeof'
console.log(typeof person.firstName); // String
console.log(typeof person.sayYourName()); // String: based on return type of the function
console.log(typeof person.blah); // Undefined

//  2. Discovering if an Object has a particular property using 'hasOwnProperty'
console.log(person.hasOwnProperty('lastName')); // True
console.log(person.hasOwnProperty('sayYourName')); // True
console.log(person.hasOwnProperty('blah')); // False

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s