JSlang.dev

JavaScript Deep Dives with Wolfram. Since 2015
Inclusive, Test-Driven, Spec-Focused, Collaborative.

September 07, 2017
TestsSource
(function(){Function, function, () => {}, ...})()

Source Code

The source code we wrote during the event.

import assert from 'assert';

describe('function session', () => {
  
  describe('`bind()`', () => {
    it('(old style) function returning `this` returns its bound context', function() {
      function f() { 
        return this; 
      }
      const boundF = f.bind('string');
      assert.equal(boundF(), 'string')
    });
    
    it('arrow function returning `this` returns the outer context', () => {
      const that = this;
      const f = () => { 
        return this; 
      }
      const boundF = f.bind('string');
      assert.strictEqual(boundF(), that);
    });
    
    it('arrow function returning `this` returns the outer context', function() {
      this.x = 'hello';
      const f = () => { 
        return this.x; 
      }
      const boundF = f.bind('string');
      assert.strictEqual(boundF(), 'hello');
    });
    
    it('old-style function, can bind arguments', () => {
      function f(x) { 
        return x; 
      }
      const boundF = f.bind(null, 42);
      assert.equal(boundF(), 42)
    });
    
    it('arrow functions, can bind arguments', () => {
      const f = (x) => { 
        return x; 
      }
      const boundF = f.bind(null, 42);
      assert.equal(boundF(), 42)
    });
  });
  
  describe('`arguments`', () => {
    it('old-style function, provides `arguments` (length)', () => {
      function f() { 
        return arguments.length; 
      }
      assert.equal(f(23, 'fourty-two'), 2)
    });
    it('old-style function, provides `arguments`', () => {
      function f() {
        return arguments; 
      }
      assert.equal(f(23, 'fourty-two')[0], 23);
      assert.equal(f(23, 'fourty-two')[1], 'fourty-two');
    });
    it('arrow function returns arguments of the parent function', () => {
      const f = (function() {
        const f1 = () => {
          return arguments; 
        };
        return f1;
      })('oh my god');
      assert.equal(f(1,2)[0], 'oh my god')
    });
  });
  
  describe('`this`', () => {
    it('does NOT bubble up, for an old-style function', function() {
      const thisOutsideOfFunction = this;
      const f = (function() {
        return function() {
          return this; 
        }
      }).apply({context: '---'});
      // assert.strictEqual(f(), undefined);
    });
    it('does bubble up, for an arrow function', function() {
      const thisOutsideOfFunction = this;
      const f = (function() {
        return () => {
          return this; 
        }
      }).apply({context: '---'});
      assert.strictEqual(f().context, '---');
    });
  });
});