0
什麼是隔離線程? 我發現它後面的文章。webworkers中的孤立線程是什麼?
Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file.
通常,線程的過程的子集。所以我想知道他們是如何孤立的?
什麼是隔離線程? 我發現它後面的文章。webworkers中的孤立線程是什麼?
Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file.
通常,線程的過程的子集。所以我想知道他們是如何孤立的?
他們是孤立的,他們沒有與主頁面的JavaScript共享相同的JavaScript全局執行上下文。他們可以與頁面的主要(UI)JavaScript進行交互的唯一方式是發送和接收消息(postMessage
和相關的message
事件)。
這裏是表明勞動者具有不同的全球環境下運轉的一個實例:
page.html
:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Isolated Worker</title>
</head>
<body>
<script>
// A global variable
var answer = 42;
(function() {
// We see answer
display("UI: typeof answer = " + typeof answer);
// Worker doesn't
var worker = new Worker("worker.js");
worker.onmessage = function(e) {
display(e.data);
};
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
worker.js
:
this.postMessage("Worker: typeof answer = " + typeof answer);
輸出:
UI: typeof answer = number Worker: typeof answer = undefined
正如你所看到的,工作人員看不到主頁的全局變量;他們處於不同的全局執行環境中。
非常感謝 – wordpressm