问题
I thought I understood wel the "this" keyword until I saw this code :
<body>
<button onclick="go()">clic1</button>
<button id="btn">clic2</button>
<script>
function go() {
console.log(this);
}
var btn = document.getElementById("btn");
btn.onclick = function() {
console.log(this)
}
</script>
</body>
I have a HTML document with two buttons that do the same thing when clicked :they log the "this" keyword.
I'm very surprised they don't show the same result :
For the button "clic1" : this = Window
For the button "clic2" : this = the button object with id "btn"
Is there any explanation for that ?
Thank you
回答1:
TLDR:
go is not the event handler of the first button. The event handler is an anonymous function generated by the HTML parser. In the example, the generated handler just happens to call go.
JavaScript code provided in HTML for an onEventName attribute is compiled into a function of form
function(event) {
// code written in the attribute value
}
Functions generated by the parser in this way have a rather strange scope chain which includes the element the generated handler is a property of, any outer form element the element is within, and the document object, at least. Reasons for the scope chain date back to before the DOM was standardized. Older IE releases provided window.event instead of the event parameter.
So the first button
<button onclick="go()">clic1</button>
in current browsers generates the button's onclick handler as:
function( event) {
go()
}
- the onclick handler is the function taking the
eventparameter. It is called with athisvalue of the button. gois an ordinary function call - thethisvalue of the caller has not been applied. You could, say, pass onthisas a parameter by callinggo(this)if you wanted to.gowas declared using thefunctionkeyword and by default has athisvalue of the global object.
In the second example, you compile an anonymous function expression normally (not using the HTML parser) and attach it directly to the second button element.`
the attached function is called with the button as its
thisvalue which can be logged to the console.the attached function does not have a wierdo scope chain.
来源:https://stackoverflow.com/questions/50742736/this-inside-event-handler-from-html-attribute