简体   繁体   中英

Why am I able to assign a value to a read only property?

Apologies if this is a simple question. On this webpage:

https://datatables.net/examples/api/form.html

I am using the following javascript to assign a value to an input element:

var node = document.evaluate("//tr[contains(td/text(), 'Angelica Ramos')]/td[2]/input", 
  document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
node.singleNodeValue.value = "abc";

Result:

The input box value updates.

On reading about XPathResult.singleNodeValue it states:

The read-only singleNodeValue property of the XPathResult interface returns a Node value or null in case no node was matched of a result with XPathResult.resultType being ANY_UNORDERED_NODE_TYPE or FIRST_ORDERED_NODE_TYPE.

So, how is it that I am able to assign to the underlying object via this property?

Answer attributable to @Felix Kling

JavaScript doesn't throw an error if you assign to readonly properties, but the value isn't actually changed. Try

var o = {}; Object.defineProperty(o, test, {readonly: true, value: 42}); o.test = 21; console.log(o.test);

node.singleNodeValue is read only, but not node.singleNodeValue.value . Read only means that you cannot assign a new value to the property, but it doesn't imply that you cannot change mutable values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM