了解代码中使用的JavaScript语法



我找到了此JavaScript代码,该代码允许异步上传文件,但这些部分是我不了解的部分。任何指示或解释都非常感谢 - 预先感谢,

// Ajax File upload with jQuery and XHR2
// Sean Clark http://square-bracket.com
// xhr2 file upload
// data is optional
$.fn.upload = function(remote, data, successFn, progressFn) {
    // if we dont have post data, move it along
    if (typeof data != "object") {
        progressFn = successFn;
        successFn = data;
    }
    //What is doing here?
    return this.each(function() {
        if ($(this)[0].files[0]) {
            var formData = new FormData();
            formData.append($(this).attr("name"), $(this)[0].files[0]);
// What's it doing here?

this的值是对调用upload的对象的引用。好像您在这里谈论一个jQuery对象。

因此调用了this.each(...,将其传递给回调函数。因为在该调用之前有一个return语句,因此.each()返回的值是从upload函数返回的,我相信在这种情况下,它将是相同的this值。

这是一个简化的演示:

// constructor function
function Test() {
  this.counter = 0;
}
// instance methods
Test.prototype.upload = function() {
  // `this` refers to the object in which `upload` was called, so it
  // has access to the `foo` method, which it invokes.
  return this.foo(function() {
    return "foo was called";
  });
};
Test.prototype.foo = function(callback) {
  // The `foo` method expects a callback function, which it invokes and
  // logs whatever the callback returned. It then returns the `this`
  // object to the caller.
  console.log(callback());
  return this;
};
var t = new Test();
var res = t.upload();
console.log(t === res);

最新更新