0

I have been making a videogame with javascript. However, there is just one thing that I don't understand.

if (!user.hasOwnProperty('firstName')) {
    $('#inputSubmit').click(function () {
        user.firstName = getInput();
        addText_1("Good, now type your character's last name");
    });
};

this statement will keep executing. Basically the condition is that the user does't have a first name property and the function will add the first name on the click of submit. However, you can keep pressing the submit button and it will keep adding the text.

$('#inputSubmit').click(function() {
    if(!user.hasOwnProperty('firstName')) {
        user.firstName = getInput();
        addText_1('hello');
    };
});

However, this works. It only does it once. Could someone explain the principle that I am not understanding?

Thank you very much!

1
  • Where do you run the code in your first sample? Is it possible that the submit handler is added once and not removed after the user clicks submit? Commented Nov 29, 2014 at 16:09

2 Answers 2

2

You attach a click event to #inputSubmit. This callback ignores the surrounding if statement. In your second sample code, if is inside the callback function.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess it makes sense. I will accept your answer in 10 minutes. Thank you!
Also, as a general design principle, you are best assigning your handlers and then checking the logic inside them, which your second format does. If you will never handle clicks unless some certain app-wide or page-wide or global condition is true, then fine, but in this case you are saying, "if the user has not filled something in, don't do the click processing. That is better inside.
0

in first code "hasOwnProperty" checked in outer scope of function() but in second code the condition checked in scope of function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.