【问题标题】:Explaining JavaScript construct解释 JavaScript 构造
【发布时间】:2017-03-02 15:26:17
【问题描述】:

谁能解释一下这个 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);
};

【问题讨论】:

  • 这段代码是单独在文件中还是片段?
  • 它似乎是对 json 文件进行 ajax 调用的对象/模块的一部分,然后使用它自己的构造方法将其自身的 files 和 files_container 属性设置为结果,该构造方法添加在阿贾克斯调用。完成后,它使用这些属性作为参数执行自己的 listFiles 函数。前两行,this.filesthis.file_container 实际上并没有做任何事情。

标签: javascript ajax


【解决方案1】:

好吧,我假设这段代码是一个模块的片段。如果它单独存在于文件中,则为“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?

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多