質問

Im new to js and its sometimes hard for me to get used to its code conventions. So i have a question, how i should declare function expression? Look at my code, is it right how i did it, or there are better practices?

function onAddButtonClick() {
    var engWord = document.getElementById('engWord'),
        japWord = document.getElementById('japWord'),
        engVal = engWord.value,
        japVal = japWord.value,
        engExpr = (engVal !== ""),
        japExpr = (japVal !== ""),
        duplicateNum,
        checkImg,
        numOfWords;

    duplicateNum = (function () {
        var i,
            pair;

        for (i = 0; i < dictionary.length; i++) {
            pair = dictionary[i];
            if (pair.eng === engVal && pair.jap === japVal) {
                return 3;
            } else if (pair.jap === japVal) {
                return 2;
            } else if (pair.eng === engVal) {
                return 1;
            }
        }
        return 0;
    }());

    //remove focus from inputs
    engWord.blur();
    japWord.blur();
    ...
}

Thanks in advance.

役に立ちましたか?

解決

You did fine. Using the opening ( is not syntactically required in this context, but it makes a great warning to the human reader of the code about what is going on. The convention helps.

At the end, the invoking parens () can go inside, or outside, the closing ). Doug Crawford recommends inside and many linters check for this. Despite his claims of dog balls1, it really doesn't matter.

By the way, the idea of function expression being declared and then immediately running is called an IFFE -- Immediately Invoked Function Expression

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top