addEventListener
即時無名関数の内部での
使用にスコープの問題があるようです。
イベントリスナーの内部で、(コンストラクターとを使用して)イミディエート関数の外部で構築されるJavascript「クラス」のインスタンスを作成していますprototype
。
グッドプラクティスを維持するために、私は即時関数を使用してグローバル変数addEventListener
を回避し、インラインJavascriptの使用を回避したいと思いました(したがって、HTMLから分離しました)。
では、スコープの問題を発生させずにこれを正しく行うにはどうすればよいでしょうか。また、そうするためのグッドプラクティスは何ですか。
これが私のhtmlです:
<html>
<head>
<title>asdf</title>
</head>
<body>
<input type = "text" id = "userInput" />
<input type = "button" id = "submitButton" value = "submit" />
<script type = "text/javascript" src = "asdf.js" />
</body>
</html>
...そしてこれが私のJavascriptですasdf.js
(これは機能していません):
// constructor for object-oriented processing of the user input
function Statement(expression)
{
this.expression = expression;
}
// instance method
Statement.prototype.checkSyntax = function()
{
var newExp = this.expression;
return newExp;
};
// immediate anonymous function
(function()
{
var submitButton = document.getElementById("submitButton");
// event listener for the submit button
submitButton.addEventListener("onclick", function(event)
{
var userInput = document.getElementById("userInput");
// creating a new object with constructor above
var expr = new Statement(userInput);
// calling instance method of the "class" Statement
alert(expr.checkSyntax() );
// disable the button after first use
event.stopImmediatePropagation();
}, false);
})(); // end of immediate anonymous function