问题
I'm not even sure exactly what I'm asking here. I just know it isn't what I expected.
I have a page script (see below) that grabs a reference to an element by its ID, then calls a few functions on it. Each function logs the element (or its textContent
) to the console, modifies the text contents, then calls the next function. What confuses me is how those changes are logged.
If I log element.textContent, I get the behavior I expected: Each log prints the string as left by the previous function.
If I log the element itself, I get a different behavior*: Each log outputs the element in its final state, not its state when the log was called.
This leads me to think that the element is passed by reference, resulting in all the references being updated together as the script continues, while the element's text contents are logged by value.
If this is true, how do I know which behavior to expect? Are all DOM references passed by reference, while strings (primitives) by value? As I understand it, JavaScript passes objects by reference and primitives by value. Is that what’s happening here?
*The output from JS Bin is far more verbose that Chrome gives—but it does describe the elements as of type object
, however. The full code I was using is (using element.textContent
, not element
) below.
<html>
<body>
<p id="paragraph">First paragraph</p>
<script>
(function () {
'use strict'
var one = function () {
console.log(example.textContent)
example.textContent = example.textContent.replace('paragraph', 'call')
two()
}
var two = function () {
console.log(example.textContent)
example.textContent = example.textContent.replace('First', 'Second')
three()
}
var three = function () {
console.log(example.textContent)
example.textContent = example.textContent.replace('Second', 'Third')
console.log(example.textContent)
}
var example = document.getElementById('paragraph')
console.log(example.textContent)
one()
})()
</script>
</body>
</html>
回答1:
If this is true, how do I know which behavior to expect?
Read the documentation for the relevant API. For example, the HTML5 specification for the DIV element includes a link to the interface HTMLDivElement API that tells you what various methods and properties return.
Unfortunately, HTML5 doesn't include all relevant information, so you also have to check other specifications such as the W3C DOM Core for textContent.
You can also look around the Mozilla Developer Network (MDN) for various web APIs. Probably the simplest way is to just call the method or access the property and see what it returns using typeof.
来源:https://stackoverflow.com/questions/25840318/are-dom-elements-passed-by-reference-to-console-log