浏览w3schools tutorial for JavaScript,发现如下声明:
A global variable has global scope: All scripts and functions on a web page can access it.
所以,我的查询是,我们有办法引用在特定网页中声明的变量吗?
例如,在C中,我们有extern关键字,使用它我们可以访问在另一个文件中声明的变量,但是我们可以在我们的文件中引用它.
例如:
在fileA.html的内部脚本标记中,我们声明了var x = 50,在function()声明之外,因此它是全局w.r.t fileA.html.
如果我有fileB.html,我们可以从fileB.html中体现的脚本标签中引用x吗?
需要明确的是,这不是跨网页重用JavaScript文件的情况.
解决方法:
你可以用Web Workers
; MessageChannel
,见How to clear the contents of an iFrame from another iFrame;或window.postMessage()
在浏览上下文之间传递或传递变量.
利用SharedWorker
的方法
fileA.html
<!DOCTYPE html>
<html>
<head>
<script src="scriptA.js"></script>
</head>
<body>
<a href="fileB.html" target="_blank">fileB</a>
</body>
</html>
scriptA.js
var x = 50, p;
var worker = new SharedWorker("worker.js");
worker.port.addEventListener("message", function(e) {
alert(e.data);
if (!p) {
p = document.createElement("p");
p.innerHTML = e.data;
document.body.appendChild(p)
}
}, false);
worker.port.start();
console.log("Calling the worker from fileA")
worker.port.postMessage(x); // post `50` to worker
fileB.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="scriptB.js"></script>
</head>
<body>
</body>
</html>
scriptB.js
var x, p;
var worker = new SharedWorker("worker.js");
worker.port.addEventListener("message", function(e) {
if (!x && !p) {
x = e.data; // at `connections`:`1` : `e.data`:`50`
p = document.createElement("p");
p.innerHTML = "Message from fileA:" + x;
document.body.appendChild(p)
}
}, false);
worker.port.start();
console.log("Calling the worker from fileB");
worker.port.postMessage("");
worker.js
self.x = null, connections = 0;
onconnect = function(e) {
var port = e.ports[0];
++connections;
port.addEventListener("message", function(e) {
if (!self.x) {
self.x = e.data;
port.postMessage("Received:" + self.x
+ " from fileA, total connections:"
+ connections);
} else {
port.postMessage("fileB received:" + self.x
+ " total connections:"
+ connections);
}
});
port.start();
}