April 29, 2024
TestsSource
- Order of execution of nested functions
- Function names
- Can we write a getter for fn.bind()?
- Can we use `this` inside any function?
Source Code
The source code we wrote during the event.
test.js
import {strict as assert} from 'assert';
describe('Order of execution of nested functions', () => {
it('a function1 can return a nested function2', () => {
function function1() {
return function function2() {
return 42;
}
}
assert.equal(function1()(), 42);
});
});
describe('Function names', () => {
it('a function1 returns a function2', () => {
function function1() {
return function function2() {}
}
assert.equal(function1.name, 'function1');
assert.equal(function1().name, 'function2');
});
it('renaming a function by setting .name does NOT work', () => {
function fn1() {}
assert.throws(() => fn1.name = 'fn3');
});
it('a function can be renamed using `Reflect.defineProperty`', () => {
function fn1() {}
Reflect.defineProperty(fn1, 'name',
{enumerable: true, writable: true, configurable: true, value: 'fn1'});
fn1.name = 'holger';
assert.equal(fn1.name, 'holger');
});
it('rename a function as it is executed', () => {
function fn1() {
Reflect.defineProperty(fn1, 'name', {enumerable: true, configurable: true, writable: true, value: 'holger'});
}
assert.equal(fn1.name, 'fn1');
fn1();
assert.equal(fn1.name, 'holger');
assert.throws(() => holger.name, ReferenceError);
});
});
describe('Can we write a getter for fn.bind()?', () => {
it('fn.bind is a function', () => {
function fn() {}
assert.equal(typeof fn.bind, 'function');
});
it('fn.bind() returns a function', () => {
function fn() {}
const bound = fn.bind();
assert.equal(typeof bound, 'function');
});
it('the name of a bound function is `bound <function.name>`', () => {
function fn1() {}
const result = fn1.bind();
assert.equal(result.name, 'bound fn1');
});
it('the value of a bound function can be accessed via `this`', () => {
function fn1() {
assert.equal(this, '...');
}
const bound = fn1.bind('...');
const bound1 = bound();
});
});
describe('Can we use `this` inside any function?', function() {
it('inside an arrow function `this` is the lexical context', () => {
globalThis.key = 'not the value';
function fnOuter() {
return () => this;
}
assert.equal(fnOuter()(), undefined);
const instance = new fnOuter();
assert(instance() instanceof fnOuter);
});
it('returning `this` from a function returns undefined (in strict mode)', function() {
function fn() {
return this;
}
assert.equal(fn(), undefined);
});
});