user4406203
user4406203

Reputation: 33

Javascript error object is not a function: why the code needs window.?

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>

Upvotes: 0

Views: 95

Answers (1)

Quentin
Quentin

Reputation: 943569

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.

Upvotes: 2

Related Questions