April 27, 2023
TestsSource
- Do functions have a prototype?
- Create own object with a custom prototype
Source Code
The source code we wrote during the event.
protoype.spec.js
import {strict as assert} from 'assert';
describe('Do functions have a prototype?', () => {
it('a function has a property prototype of type object', () => {
function Foo() {}
assert.equal(typeof Foo.prototype, 'object');
});
it('a function has a prototype with the property `constructor`', () => {
function Foo() {}
assert.equal(typeof Foo.prototype.constructor, 'function');
});
it('applying `new` to a function creates an object with a constructor property with the function', () => {
function Foo() {}
const foo = new Foo();
assert.equal(foo.constructor, Foo);
});
});
describe('Create own object with a custom prototype', () => {
it('applying new to a function creates an object, which contains the custom prototype property', () => {
function Foo() {
}
Foo.prototype.f = 'the f in the prototype';
const foo = new Foo();
assert.equal(foo.f, 'the f in the prototype');
});
it('we add to the prototype chain, by assigning a function to the prototype property', () => {
function Foo() {
this.innerF = 'in Foo';
}
function Bar() {
this.innerB = 'in Bar';
}
Foo.prototype = new Bar();
const foo = new Foo();
assert.equal(foo.innerB, 'in Bar');
});
it('assigning a simple object to a prototype, acts like adding something to the prototype chain', () => {
function Foo() {}
Foo.prototype = {inTheChain: true};
assert.equal(new Foo().inTheChain, true);
});
it('assigning a function to a prototype, the properties of that function are on the prototype chain', () => {
function Foo() {}
function funcWithAProperty() {}
funcWithAProperty.some = 42;
Foo.prototype = funcWithAProperty;
assert.equal(new Foo().some, 42);
});
it('DONT DO THIS a prototype chain can be of arbitrary depth', () => {
function Foo() {}
Foo.prototype = {__proto__: {__proto__: {some: 'one'}}};
assert.equal(new Foo().some, 'one');
});
});