无法在函数内部访问Javascript全局对象

时间:2017-06-20 22:22:07

标签: javascript node.js

我遇到了对象范围的问题,但我很难理解为什么:

'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:无法读取未定义

的属性'dayLights'

即使只是:

function inside() {
    console.log(dayLights);
}

inside();

以同样的方式失败。

如何从函数中访问全局对象?

1 个答案:

答案 0 :(得分:1)

如果你想在&#39; inside&#39;内部创建上下文。功能与外部上下文相同:

inside.bind(this)()

或者:

var self = this
function inside() {
    var toCycle = 'dayLights';
    console.log(self[toCycle]);
}