未声明的局部变量变为全局变量。它们最终在文档中的什么位置?

时间:2018-12-22 23:23:29

标签: javascript oop inheritance javascript-objects hoisting

我对未声明的变量发生什么以及它在文档中的末尾位置缺乏了解。例如

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}
}
b();
console.log(a);

起重将变为

function b () {
  function a() {}
   a = 10;
   return;
}

var a;
a = 1;
b();

console.log(a); // output 1

a = 10被分配给功能b的功能a。这使a = 1可以分配给var一个声明。现在,如果我们将功能a注释掉,我们将获得不同的输出。

function b () {
 // function a() {}
   a = 10;
   return;
}

var a;
a = 1;
b();

console.log(a); // output 10

因此,现在将= 10分配给未声明的变量,因此它变为全局变量,那么它到底是什么样子?由于变量突变,它会像这样放在文档的底部吗?

function b () {
 // function a() {}

   return;
}

var a;
a = 1;
b();
a = 10;

console.log(a); // output 10

这正确吗?

1 个答案:

答案 0 :(得分:0)

在您的情况下,未将10分配给未声明的变量。 import UIKit import AVKit import PlaygroundSupport let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) container.addSubview(imageView) PlaygroundPage.current.liveView = container PlaygroundPage.current.needsIndefiniteExecution = true func previewImageFromVideo(url: NSURL) -> UIImage? { let url = url as URL let request = URLRequest(url: url) let cache = URLCache.shared if let cachedResponse = cache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data) { return image } let asset = AVAsset(url: url) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true imageGenerator.maximumSize = CGSize(width: 250, height: 120) var time = asset.duration time.value = min(time.value, 2) var image: UIImage? do { let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil) image = UIImage(cgImage: cgImage) } catch { } if let image = image, let data = image.pngData(), let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) { let cachedResponse = CachedURLResponse(response: response, data: data) cache.storeCachedResponse(cachedResponse, for: request) } return image } imageView.image = previewImageFromVideo(url: NSURL(string: "https://www.w3schools.com/html/mov_bbb.mp4")!) 中的所有逻辑一经调用就执行。发生这种情况时,已经声明了function b,并且已经为其分配了b

由于在a的局部变量环境中没有变量1,因此将其分配给在父变量环境中可以找到的下一个a

您可以通过最初将function b声明为const来测试此行为。将无法在函数中重新分配a

a