0

I've got 2 different ways to code the World function. The first is an example from Cucumber.js's website. This is extending their existing World object basically. And the second example commented out is me taking that first example code and getting rid of that world variable and passing nothing in the callback. My code works too.

Question: Why would they be sending a variable like this in a callback? Is there any advantage to that? Because in my example, I'm already extending the existing World object by simply setting properties in my example.

I'm sorta still new to callbacks...

"use strict";

var hooks = require('../support/before_hooks.js');
var zombie = require('zombie');

// their example
var World = function World(callback) {

    var browser = new zombie();

    var world = {
            browser: browser,
            visit: function(url, callback) {
            this.browser.visit(url, callback);
        }
    };

    callback(world);
};

// my example
//var World = function World(callback) {

//    this.browser = new zombie();
//    this.visit = function(url, callback) {
//                    this.browser.visit(url, callback);
//                };

//    callback();
//};

module.exports.World = World;
PositiveGuy
  • 17,621
  • 26
  • 79
  • 138
  • 1
    the code given to callback might want those arguments, even if the callback still "fires" without them. the first one also allows generic invocation/application whereas yours counts on function side-effects, unless you use "new ", which the orig doesn't need. in short, your callback handles the _when_, but not the _what_... – dandavis Apr 11 '15 at 23:24

1 Answers1

0

The key difference between 'their example' and 'my example' is who is instantiating the world object. In 'their example', you have instantiated that object yourself and Cucumber will use that object in your Step Definitions. On the other hand, in 'my example' you are telling Cucumber that it should instantiate a world object using the World() function as the constructor.

As for the advantages of 'their example', the one big one that I can see is that instantiating the object yourself allows you to scope it how ever you see fit. For instance, you could go so far as to instantiate it on the global object so that you can access it from anywhere else in your code. In contrast, in 'my example' the world object would only be accessible by your Step Definitions.

On a side note, if you look at the World section of the Cucumber.js README, you'll see that they provide both 'their example' and 'my example' as examples.

Nathan Thompson
  • 2,354
  • 1
  • 23
  • 28