解释JavaScript构造

时间:2017-03-02 15:26:17

标签: javascript ajax

任何人都可以解释一下这个javascript / ajax代码吗?我将此代码用于FileManager(使用jsTree)。

this.files;
this.file_container;

var obj = this;

$.ajax
({
    url: 'ajax_requests.php?link=allFile',
    success: function (result)
    {
        obj.construct(JSON.parse(result));
    }
});

this.construct = function construct (files)
{
    this.files = files;
    this.file_container = $('#file_container');

    this.listFiles(this.files, this.file_container);
};

1 个答案:

答案 0 :(得分:0)

好吧,我假设这段代码是模块的一个片段。如果它在文件中单独使用" this。"没有多大意义。

this.files;              // these 2 lines declarations of properties of 
this.file_container;     // the module. They aren't necessary once the 
                         // properties are created on first assign, 
                         // but it could be justa way of make code 
                         // more clear/readable

var obj = this;

$.ajax // this is an ajax call to...
({
    url: 'ajax_requests.php?link=allFile',   // ... this url ...
    success: function (result) //...which calls this function on success...
    {
        obj.construct(JSON.parse(result)); 
        //...then, as obj = this, calls contruct method with the JSON parsed 
        // ajax's call result. So the ajax call returns a JSON that is 
        // transformed to object by the JSON.parse method. Then this object is 
        // used as parameter to construct method.

    }
});

this.construct = function construct (files)
{
    this.files = files; 
    // assigns previous declared files property to the result of ajax call
    this.file_container = $('#file_container'); 
    // assigns previous declared file_container property to the jscript object
    // representing the DOM element whose id is 'file_container'.

    this.listFiles(this.files, this.file_container); 
    // calls a method called listFiles (which is not present in this fragment), 
    //having as parameters the 2 properties files and file_container.
};

如果您不知道AJAX是什么,请查看:What is AJAX, really?