Don't get stuck on paradigms

Doing my favourite procrastination of reading JavaScript articles I found this great article about why use closure. And it become more clear why you guys want shorter lambda's: arrow functions (anonymous functions).

I've written about how to write closures before and this will be another posts on how to do it right.

Use named functions!

In the article I found, about "why use closures", there's some interesting code examples and an interesting outcome ...

// Define the constructor
function Person(name, age) {

  // Store the message in internal state
  this.message = name + ", who is " + age + " years old, says hi!";


// Define a method
Person.prototype.greet = function greet() {

var message = "I'm in the scope yo!";

// Create a new person
var bob = new Person("Bob", 47);

setTimeout(bob.greet, 100);
// Outputs: I'm in the scope yo! Or undefined in NodeJS

Notice what happens when the method greet is passed to setTimeout!

setTimeout will run the function and this in bob.greet will refer to the global scope (browser) or the setTimeout function (node JS).

Here are some ways to overcome this problem :

// Anonymous function:
setTimeout(function () {
}, 100);

// same thing but with an arrow (ES6):
setTimout( () => {
}, 100);

// or using bind:
setTimeout(bob.greet.bind(bob), 100);

Make it simpler

Do we really need to take the Object Orientated (OO) approach?
And how can we avoid anonymous functions!?
Here's how you can do it without classes/prototype and instead use plain JavaScript objects.

var person = [];

person.push({name: "Bob", age: 47});
person.push({name: "Tim", age: 28});

function greetAll() {
	for(var i=0; i<person.length; i++) {
		console.log(person[i].name + ", who is " + person[i].age + " years old, says hi!");

setTimeout(greetAll, 100);

Written by 6:th August 2015.

Follow me via RSS:   RSS https://z├Ą (copy to feed-reader)
or Github:   Github