0

I am having trouble understanding the difference between

var maxResult = window.max(maxValInt1, maxValInt2);

that works well, and

var maxResult = max(maxValInt1, maxValInt2);

that gets a error "object is not a function".

Why do I need to add window. before the max function?

I'm new in Java Script and it's helpful if you can explain with detail.

<div id="maxOfTwo">Max function: <input type = "number" name="val1" value="0">, <input type = "number" name="val2" value="0"> = <span></span></div>

<script type="text/javascript">

function max(val1, val2){
    if(val1 > val2){
        return val1;
    }else{
        return val2;
    }
}

window.onload = function() {
    var max = document.getElementById("maxOfTwo");
    var maxNumber1 = max.children[0];
    var maxNumber2 = max.children[1];
    maxNumber1.addEventListener("blur", doMax);
    maxNumber2.addEventListener("blur", doMax);
    function doMax() {
        var maxValue1 = maxNumber1.value;
        var maxValue2 = maxNumber2.value;
        var maxValInt1 = parseInt(maxValue1);
        var maxValInt2 = parseInt(maxValue2);
        var maxResult = window.max(maxValInt1, maxValInt2);
        max.children[2].innerHTML = maxResult;
    }
}
</script>

1 Answer 1

2
var max = document.getElementById("maxOfTwo");

You have a locally scoped variable with the same name.

If you don't explicitly access the property of the window object, then the scope chain will find your HTML Element Object first.

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

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.