0
var use_ajax = new function()
{
    var ajax = new XMLHttpRequest();
    var keyword = '';
    var text = '';
    var array_data = Array();
    this.get_data = function(keyword)
    {
        ajax.open("GET", "proc.php?keyword=" + keyword, true);
        ajax.send();
    }
    ajax.onreadystatechange = function()
    {
        if(ajax.readyState == 4 && ajax.status == 200)
        {
            text = '';
            array_data = JSON.parse(ajax.responseText).data;
            for(var i=0; i<array_data.length; i++)
            {
                text += array_data[i];
            }
            document.getElementById('list').innerHTML = text;
        }
    }
}

Even if I delete var from var use_ajax = new function() in my code, it works correctly. Why?

Even if I delete var array_data = Array(); in my code, I don't get a 'not defined' error for array_data variable. Why?

Saturn
  • 55
  • 10
  • 2
    You're just creating a global without the var. While the code might still work, unexpected things may happen. – baao Jul 14 '17 at 07:13
  • 3
    put 'use strict'; at line 1, of your code . And tell us if javascript works equal. – Álvaro Touzón Jul 14 '17 at 07:13
  • 3
    If you want to throw error then use `'use strict';` at top of your JS code https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode – Muthu Kumaran Jul 14 '17 at 07:14
  • @baao Could you explain more about 'global without the var'? How can I create 'global with the var'? – Saturn Jul 14 '17 at 07:16
  • @MuthuKumaran Thank you. An error message now appears correctly. Could you please explain the `var array_data = Array ();` part? – Saturn Jul 14 '17 at 07:19
  • 1
    [Never ever use `new function() {…}`!](https://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key-as-static) – Bergi Jul 14 '17 at 07:23

0 Answers0