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

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a comment