jbrunton / core-js

2 stars 1 forks source link

OOP-ify the mediator #8

Open jbrunton opened 12 years ago

jbrunton commented 12 years ago

Global state is bad, and complicates testing. The mediator.js file should return a Mediator object constructor (instead of an object instance as it does now).

This will require changes (all in core-js) to:

To run the tests, open SpecRunner.html (in the core-js-blog-demo project) in a browser, and ensure they all pass (I think I commented out the ones which were failing..)

jbrunton commented 12 years ago

Note: current, _channels and _waits are variables private to the RequireJS module.

There are a couple of options for dealing with private variables when using object constructors. One is to keep the variables truly private by defining the dependent functions in the constructor itself. The other is to use a convention (like an underscore prefix) to denote that the fields shouldn't be directly referenced, so that you can then reference the variables through functions on the prototype. For example:

Option 1:


var MyObject = function(foo) {
    this.alert = function() {
        // here, foo is private to each instance
        alert(foo);
    };
};

// ie, instances do not have a foo variable, due to Javascript's function scoping
var obj = new MyObject("hi!");
obj.alert();
console.log(typeof(obj.foo)); // "undefined"

Option 2:


var MyOtherObject = function(foo) {
    this._foo = foo;
};

MyOtherObject.prototype.alert = function() {
    alert(this._foo);
};

var obj2 = new MyOtherObject("hi!");
obj2.alert();
console.log(typeof(obj2._foo)); // "string" - ie, the variable isn't really private

I'm undecided which is preferable, but we should pick a convention. I'm inclined to suggest the latter approach: partly, because it'll make debugging easier (as you can inspect object state more easily); and also because it's easier to read code if functions are defined on the prototype, rather than all crammed into the constructor.