我遇到了对象范围的问题,但我很难理解为什么:
'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]);
这一切都运行得很好。然后,当我尝试移动最后几行以输出对象时,但这一次是在函数内,如下所示:
function inside() {
var toCycle = 'dayLights';
console.log(this[toCycle]);
}
inside();
它失败了:
TypeError: Cannot read property 'dayLights' of undefined
即使只是:
function inside() {
console.log(dayLights);
}
inside();
以同样的方式失败。
如何从函数内访问全局对象?
最佳答案
如果您想让“内部”函数内的上下文与外部上下文相同,您可以:
inside.bind(this)()
或者:
var self = this
function inside() {
var toCycle = 'dayLights';
console.log(self[toCycle]);
}
关于Javascript全局对象无法在函数内部访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663933/