Bomber Bomber - 11 days ago 6
Javascript Question

Arrow functions bound at definition time

I'm learning es6 arrow functions, how I can get this test to pass?

describe('arrow functions have lexical `this`, no dynamic `this`', () => {

it('bound at definition time, use `=>` ', function() {
var bound = new LexicallyBound();
var fn = () => getFunction();

assert.strictEqual(fn(), bound);
});

Answer

Since the function returned by getFunction doesn't do anything to demonstrate that it closes over this, I don't think it's of any use to use you here.

If the goal is to prove that arrow functions are lexically bound (that is, that they close over this), then:

it('is lexically bound', function() {
    const obj = {
        arrow: () => {
            return this;
        }
    };
    assert.strictEqual(obj.arrow(), this);
});

If arrow didn't close over this, it would return obj, not the current value of this in that callback.

Example:

function it(label, test) {
  try {
    test();
    console.log(label, "OK");
  } catch (e) {
    console.log(label, "FAILED", e.message);
  }
}
const assert = {
  strictEqual(a, b) {
    if (a !== b) {
      throw new Error("a == b was false");
    }
  }
};

it('Arrow function is lexically bound', function() {
  const obj = {
    arrow: () => {
      return this;
    }
  };
  assert.strictEqual(obj.arrow(), this);
});


it('Non-arrow function is not lexically bound', function() {
  const obj = {
    nonarrow: function() {
      return this;
    }
  };
  assert.strictEqual(obj.nonarrow(), obj);
});