I'm running in to a problem with object scope, but I 'm struggling to grasp why:
'use strict';
// Build array of equipment, connected pin, and default state
var equipmentData = [{shortName: 'dayLights', longName: 'Day lights', pin: 1, state: true},
{shortName: 'nightLights', longName: 'Night lights', pin: 2, state: false}];
// Constructor build a new object
var Equipment = function(shortName, longName, pin, state) {
this.shortName = shortName;
this.longName = longName;
this.pin = pin;
this.state = state;
console.log('Created object for ' + this.longName);
}
// Loop through the array and create an object for each
for (var i = 0; i < equipmentData.length; i++) {
var equipmentName = equipmentData[i].shortName;
this[equipmentName] = new Equipment(equipmentData[i].shortName, equipmentData[i].longName, equipmentData[i].pin, equipmentData[i].state);
}
// Pick what you now want to review
var toCycle = 'dayLights';
console.log(this[toCycle]);
This all works just fine. When I then try move the last couple of lines to output the object but this time within a function as follows:
function inside() {
var toCycle = 'dayLights';
console.log(this[toCycle]);
}
inside();
it fails with:
TypeError: Cannot read property 'dayLights' of undefined
Even just:
function inside() {
console.log(dayLights);
}
inside();
fails in the same way.
How can I access the global object from within the function?