Reputation: 107
I am using a switch statement to test the name attribute of a span:
<span id = "prompt" title = "newPerson">What is your name?</span>
<button type = "button" id = "execute">Do It!</button>
<input type="text" id="input" />
document.getElementById("execute").addEventListener("click",execute);
function execute(){
var action = document.getElementById("prompt").title;
var request = document.getElementById("input").value;
if(action == "newPerson"){ alert("WTF"); } //Alerts as expected
this.act = function(action, request){
switch(action){ //Default case always gets called
case "newPerson":
person = new Person(request, 0, 0);
account = new Account(person);
break;
default:
alert("Internal Error :(");
break;
}
}
if(request == ""){
alert("No Input");
}else{
this.act();
}
}
I also tried changing it to 'newPerson'. Also i tried changing my if to use '===' instead of '==' and i still got the "WTF" alert. Seems like this should be working any ideas?
Upvotes: 0
Views: 50
Reputation: 1667
This is an easy one.
When calling this.act
you are passing no parameters - therefore the action
parameter within you function body where the switch operator is used is undefined
-> the default case is called.
You can basically change a function signature to the following
...
this.act = function(){
...
Then you'll produce a closure, and the action
and request
values will be used from the outer scope.
Or you can change this part of code, when the function is called and pass the parameters as below:
...
if (request == ""){
alert("No Input");
} else {
this.act(action, request);
}
...
Note: Usually it is a bad pattern to have the parameters of function with the same name as variables in the outer scope - it can cause misunderstanding as in your case.
Upvotes: 1