0

I've found this JavaScript code that allows to upload files asynchronously but the are some parts that I don't understand. any pointers or explanation highly appreciated - thanks in advance,

// 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]);
4
  • 1
    Mind telling us which parts? Or that whole snippet of code? Commented Sep 7, 2017 at 18:02
  • I've added a better explained comment Commented Sep 7, 2017 at 18:05
  • Honestly, all I see is overkill... It simply loops what's returned by a jQuery selector (<input type="file"> probably) and fetches the file to upload. FormData is a way to send form asynchronously. Commented Sep 7, 2017 at 18:09
  • Not to be mean, but $(this)[0] is a pretty good indicator that the author of this code doesn't really have a very deep understanding of things. It's effectively identical to just referencing this, but is wasteful with memory and CPU. Commented Sep 7, 2017 at 18:12

1 Answer 1

2
// What's it doing here?

The value of this is a reference to the object on which upload was invoked. Seems like you're talking about a jQuery object here.

So this.each(... is invoked, passing it a callback function. Because there's a return statement before that call, the value that .each() returns is returned from the upload function, which I believe will be the same this value in this case.

Here's a simplified demo:

// 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.