【发布时间】:2020-05-18 22:01:54
【问题描述】:
在这个地址的网络浏览器中:https://www.w3schools.com/js/tryit.asp?filename=tryjs_arrow_function6,我删除了原始代码,并粘贴了这段代码:
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
document.getElementById("btn").addEventListener("click", function() {
console.log(this) // **THIS LINE GAVE THE VALUE OF AS BUTTON**
});
</script>
</body>
</html>
在 React Stackblitz 中尝试了以下代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class Foo extends React.Component{
render(){
return (
<button type="button" onClick={function handleClick(event){
console.log(this); // **THIS LINE GAVE THE VALUE AS UNDEFINED**
}}>
Click Me
</button>
);
}
}
render(<Foo />, document.getElementById('root'));
为什么两个结果不同?请参考两个代码示例的 cmets。第一个代码将按钮作为 this 的值记录到控制台,第二个代码将 undefined 作为 this 的值记录到控制台。他们不应该是一样的吗?为什么它们不同?
【问题讨论】:
-
这能回答你的问题吗? How does the "this" keyword work?
标签: javascript reactjs this