理解代码中使用的Javascript语法

时间:2017-09-07 18:01:20

标签: javascript jquery ajax

我发现这个JavaScript代码允许异步上传文件,但这些是我不理解的部分。任何指针或解释都非常感谢 - 提前感谢,

function getBottomUp(node, path) {
    path = [node.value].concat(path || []);
    if (!node.left && !node.right) {
        console.log(JSON.stringify(path));
        return;
    }
    node.left && getBottomUp(node.left, path);
    node.right && getBottomUp(node.right, path);
}

var tree = { value: 8, left: { value: 3, left: { value: 1 }, right: { value: 6, left: { value: 4 }, right: { value: 7 } } }, right: { value: 10, right: { value: 14, left: { value: 3 } } } };

getBottomUp(tree);

1 个答案:

答案 0 :(得分:2)

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