在函数内部修改变量后,为什么变量未更改?-异步代码参考

JavaScript

乐A

2020-03-11

给定以下示例,为什么outerScopeVar在所有情况下未定义?

var outerScopeVar;

var img = document.createElement('img');
img.onload = function() {
    outerScopeVar = this.width;
};
img.src = 'lolcat.png';
alert(outerScopeVar);

var outerScopeVar;
setTimeout(function() {
    outerScopeVar = 'Hello Asynchronous World!';
}, 0);
alert(outerScopeVar);

// Example using some jQuery
var outerScopeVar;
$.post('loldog', function(response) {
    outerScopeVar = response;
});
alert(outerScopeVar);

// Node.js example
var outerScopeVar;
fs.readFile('./catdog.html', function(err, data) {
    outerScopeVar = data;
});
console.log(outerScopeVar);

// with promises
var outerScopeVar;
myPromise.then(function (response) {
    outerScopeVar = response;
});
console.log(outerScopeVar);

// geolocation API
var outerScopeVar;
navigator.geolocation.getCurrentPosition(function (pos) {
    outerScopeVar = pos;
});
console.log(outerScopeVar);

为什么undefined在所有这些示例中都输出我不需要解决方法,我想知道为什么会这样。


注意:这是JavaScript异步性的典型问题随时改进此问题,并添加更多简化的示例,社区可以识别。

第645篇《在函数内部修改变量后,为什么变量未更改?-异步代码参考》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
做个有心人 2020.03.11

显而易见,杯子代表outerScopeVar

异步功能就像...

异步调用咖啡

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android