首先來看一個demo:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" name="" id='test' onclick="demo(this)">
<script type="text/javascript">
function demo(this) {
console.log(this);
}
</script>
</body>
</html>
本想列印出id為test的input元素對象,結果報錯Uncaught SyntaxError: Unexpected token this
這是什麼原因呢?
仔細想了一下,将function中的參數 this 改成其他字元串試試,結果還真的不報錯了,程式正常運作。
原來是因為this是JavaScript中的關鍵字,不能在形參中作為變量名使用。
正确的代碼再看一下:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" name="" id='test' onclick="demo(this)">
<script type="text/javascript">
function demo(obj){
console.log(obj);
}
</script>
</body>
</html>
一個小小的知識點,哈哈!