[英]Why someObject = Object.assign({}, someObject, window.getSelection()) and {...window.getSelection()} does return empty object?
我嘗試將window.getSelection()
復制到someObject
以將其存儲為對象屬性以備將來重用。
我有這個代碼:
var selection = window.getSelection();
//case 1:
this.selection = Object.assign({}, this.selection, selection);
console.log(this.selection);
console.log(selection);
//---------------------------------------
//case 2:
this.selection = {...window.getSelection()};
console.log(this.selection);
console.log(selection);
在這兩種情況下(案例 1 和案例 2),我在控制台中看到了空對象{}
for this.selection
和 Selection 對象( https://developer.mozilla.org/en-US/docs/Web/API/Selection )以供selection
多變的。
我錯過了什么? 如何將 window.getSelection() 復制到this.selection
(這是一個類屬性)?
JavaScript 使用原型鏈。 當您嘗試訪問對象中的屬性時,JS 引擎會在對象中檢查該屬性,然后在對象的原型中,然后在對象的原型的原型中,等等......
直接存在於對象中的屬性稱為自己的屬性。 selection
對象沒有自己的屬性,相反,像anchorNode
這樣的anchorNode
被定義為原型中的getter。
您可以在開發者控制台中看到這一點。 它直接在對象中顯示屬性,但這只是為了便於閱讀。 它們確實在對象的原型中。
Object.assign()和spread 語法都只復制自己的可枚舉屬性,在這種情況下不起作用。
如果要保存 Selection 以供進一步使用,可以像這樣從 Range 對象恢復 Selection:
// Save Range from the current Selection
let range = window.getSelection().getRangeAt(0);
/* Suppose here the Selection object has changed */
// Restore previous Selection
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.