JS Evening

CoreJS: Functions as Objects

Functions are Objects too!

Begin with this function definition in the exercises below:

function paint(obj) {
    obj.color = 'red';
}

All functions are also objects, which has the following implications:

1) Functions can have aliases.

2) Functions can be methods of objects.

3) Functions can be arguments.

4) Functions can have properties of their own.

5) Functions can have methods of their own.

paint.useColor('turquoise');
paint(obj); // --> sets obj's color to 'turquoise'

call and apply

function paint(color) {
    this.color = color;
}
var car = {wheels:4}, fence = {length:20};
var nums = [9,5,8,2,4,11,8,2,7,1,0,99,25,3,6,42];

this pitfalls

There's a problem in the code below:

function talk() {
    console.log(this.noise);
}

var animals = [dog, cat, canary];
animals.allTalk = function() {
    this.forEach(talk);
}
animals.allTalk(); // failure!

Identify the problem and fix it! Rewrite the allTalk method of array animals to
make each animal talk. You must use function talk without changing its definition, and forEach(something). something should be a function which is not talk but instead somehow calls talk.

Instances and Factory functions

We know how to make animal instances by hand:

var dog = {
    name:'dog',
    noise:'woof',
    talk:function() {
        console.log(this.noise);
    }
}
var sheep = {
    name:'sheep',
    noise:'baaa',
    talk:function() {
        console.log(this.noise);
    }
}

Write a function to create any number of animals like those above.

Sharing Instance Methods

Write two versions of a factory which makes animal instances which all share a single copy of their talk method.

  1. First implement talk as a global function.

  2. Instead of using a global function, attach talk as a property of the factory itself, but expect it to be called through individual animals.

Samples

scratchpad

console

Diagrams

paint method

shared talk method

animal factory