<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Coffeescripter &#187; Object Oriented</title>
	<atom:link href="http://coffeescripter.com/category/object-oriented/feed/" rel="self" type="application/rss+xml" />
	<link>http://coffeescripter.com</link>
	<description>Just another developer blog</description>
	<lastBuildDate>Sun, 08 Aug 2010 11:40:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Dependency injection and IoC in Javascript</title>
		<link>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/</link>
		<comments>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/#comments</comments>
		<pubDate>Sun, 08 Aug 2010 11:40:16 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=186</guid>
		<description><![CDATA[There has been some talk lately about DI and IoC in Javascript, and other dynamic languages such as Ruby and Python. A popular opinion seems to be that these concepts are obsolete in dynamic languages, mainly because you can alter an object at runtime. This certainly makes testing easier, but testability isn&#8217;t the main goal [...]]]></description>
			<content:encoded><![CDATA[<p>There has been some talk lately about DI and IoC in Javascript, and other dynamic languages such as Ruby and Python. A popular opinion seems to be that these concepts are obsolete in dynamic languages, mainly because you can alter an object at runtime. This certainly makes testing easier, but testability isn&#8217;t the main goal of DI and IoC, it&#8217;s more of a nice side effect, and a proof of that you&#8217;re doing it right.</p>
<p>DI is about pushing object creation and wiring as high up in the application as possible, which gives you one central location for the flow of logic. </p>
<p>Code components have dependencies, whether you&#8217;re using Java or Javascript. When your UI widget needs to make a server request to fetch some content, you depend on some code to carry that out. There are usually three approaches.</p>
<p>1. Use a global symbol, such as $.ajax in the world of jQuery.</p>
<p>2. Use a service locator, something like:</p>
<pre class="brush: jscript;">
function updateCustomer(locator) {
  var server = locator.server();
  server.get(&quot;...&quot;);
}
</pre>
<p>Or having the locator being a global variable.</p>
<p>3. Only pass in what you need, like this:</p>
<pre class="brush: jscript;">
function updateCustomer(server) {
  server.get(&quot;...&quot;);
}
</pre>
<p>The first option is the simplest. $.ajax is just a global function that anyone can use. This is also why it&#8217;s the most problematic, because if anyone can use it anywhere, you will end up with no idea of which parts of your application is making Ajax calls. You&#8217;re basically saying &#8220;use any tools you like, I don&#8217;t care&#8221; to your function.</p>
<p>The second alternative passes in a service locator instead, which is better because you have control over what functionality you expose through your locator. It&#8217;s like saying &#8220;here&#8217;s a bag of tools, you can&#8217;t use any other than these, but do what you want with any of these in the bag&#8221;.</p>
<p>The third is the most straight forward. It&#8217;s like saying &#8220;here&#8217;s a screwdriver, it&#8217;s what you&#8217;re gonna use&#8221;. Since we&#8217;re just exposing the server object, there is no risk that other features using other objects will be added to our function. That is a risk with the other two solutions, since they expose more functionality than needed. Another benefit is that it&#8217;s very easy to spot what dependencies your objects have, since they are declared in the constructor. With a locator or with globals, you might have dependencies hidden in large chunks of code that are easy to miss. You are forced to think very hard about how your application is layed out, because it becomes very easy to spot if an object is doing to much, if it requires too many dependencies. You also have to think about how to pass these dependencies around.</p>
<h2>Dependency injection is hard</h2>
<p>So if the third solution is so great, how come most people use the first two? Simply because it&#8217;s hard to achieve. Using a locator is simpler, since you just pack a bag with lots of things and pass it around. But if you use the third option, you have to keep track of who wants the different tools, and make sure that they get them. You also need to make sure that everyone can&#8217;t ask for anything.</p>
<p>In other languages, there are frameworks that help you with these things. Automating object creation in a language like Java or C# is somewhat simple, because you have type hints in the constructors. You can inspect a constructor and find out what it wants. But there is no way to do that in Javascript, since it doesn&#8217;t have types or type hints. Because of this, making a DI container in Javascript is bound to get messy, because you need to define construction rules for all objects. This is problematic because new objects can&#8217;t be added to your application without modifying the wiring code.</p>
<h2>A shot at an automated container in Javascript</h2>
<p>So we now basically know what we need. A container that is semi-smart and can assemble hierarchies of objects. It needs to be able to create objects by convention instead of configuration.<br />
To achieve this, we have a few options. First off, we can cast a constructor to a string which gives us the whole method body and then parse out the argument variable names and use them to map to objects. This is a brittle and error prone idea, since someone might rename a variable and that might take down the entire application. Another option is to add a sort of type hints. Something like this:</p>
<pre class="brush: jscript;">
function Server() {
  return {
    get: function(...) {}
  };
}

function updateCustomer(server) {
  server.get(&quot;...&quot;);
}
updateCustomer.dependencies = [&quot;Server&quot;];
</pre>
<p>It&#8217;s a little unorthodox and perhaps not so Javascripty, but it makes our object more self contained. Our function still isn&#8217;t grabbing Server direcly as with a Service Locator, it&#8217;s merely saying that it would like to get some implementation that behaves like Server does. But it isn&#8217;t very pretty, because the type hints are below the function body, which can be an issue with a more lengthy function. So here&#8217;s some syntactic sugar:</p>
<pre class="brush: jscript;">
var updateCustomer = dependant(
  [&quot;Server&quot;],
  function(server) {
    server.get(&quot;...&quot;);
  }
);
</pre>
<p>The dependant function just maps the function together with the type hints, and it also gives you a simple way to check who has which dependencies. </p>
<p>So now it&#8217;s just a matter of inspecting the dependencies array of a constructor to be able to map it together. Here&#8217;s a proof of concept:</p>
<pre class="brush: jscript;">
var dependant = function(dependencies, func) {
    func.dependencies = dependencies;
    return func;
}

var Container = function() {
    var namespaces;
    var instances;
    var constructors;

    return {
        _init: function() {
            namespaces = [];
            instances = {};
            constructors = {};

            return this;
        },
        addNamespace: function(namespace) {
            namespaces.push(namespace);
        },
        get: function(klass) {
            if(!instances[klass]) {
                if(constructors[klass]) {
                    instances[klass] = constructors[klass]();
                } else {
                    instances[klass] = this.create(klass);
                };
            };
            return instances[klass];
        },
        create: function(klass) {
            for(var i = 0; i &lt; namespaces.length; i++) {
                if(namespaces[i][klass] &amp;&amp; typeof namespaces[i][klass] == &quot;function&quot;) {
                    var constr = namespaces[i][klass];
                    if(constr.dependencies) {
                        var args = [];
                        for(var j = 0; j &lt; constr.dependencies.length; j++) {
                            args.push(this.get(constr.dependencies[j]));
                        };
                        return constr.apply(namespaces[i], args);
                    } else if(constr.length == 0) {
                        return constr();
                    };
                };
            };
            throw &quot;Cannot create '&quot;+ klass +&quot;' because there isn't a registered instance or \
                   constructor, and there was no way to auto wire it.&quot;;
        },
        registerConstructor: function(klass, creator) {
            constructors[klass] = creator;
        },
        registerInstance: function(klass, instance) {
            instances[klass] = instance;
        }
    }._init();
};
</pre>
<p>And some usage code:</p>
<pre class="brush: jscript;">
var ns = {};
ns.Alerter = function() {
    return {
        alert: function() {
            alert(&quot;Mjello!&quot;);
        }
    }
}

ns.MyObject = dependant(
    [&quot;Alerter&quot;],
    function(alerter) {
        return {
            doStuff: function() {
                alerter.alert(&quot;Mjello!&quot;);
            }
        }
    }
);

var cn = Container();
cn.addNamespace(ns);

var o = cn.get(&quot;MyObject&quot;);
o.doStuff();
</pre>
<p>I haven&#8217;t used this type of DI in a Javascript application yet, so I can&#8217;t really say if it&#8217;s any good, but I get a good vibe from it so I&#8217;m planning on using it for a Javascript application that I&#8217;m about to create.</p>
<p>An added benefit here is that the <code>dependencies</code> array can contain anything, not just strings with function names. It could contain CSS selectors to let you decouple DOM access, and maybe even remove the tight coupling with a library such as jQuery or YUI. It could also contain an array of method names, something like:</p>
<pre class="brush: jscript;">
ns.MyObject = dependant(
    [[&quot;alert&quot;]],
    function(alerter) {
        return {
            doStuff: function() {
                alerter.alert(&quot;Mjello!&quot;);
            }
        }
    }
);
</pre>
<p>This says, &#8220;I need one object, and I need it to have an alert method&#8221;, which is basically a flirt with a <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural type system</a> that is a very good fit for Javascript.</p>
<h2>Conclusion</h2>
<p>Javascript is a very open language. You can choose to go OO or procedural, and you can even choose which type of OO you want to use, classical, prototypal or parasitic. It&#8217;s only natural then that there are also a number of different ways to manage dependencies in an application. So when you start a new project in Javascript, you have a smörgåsbord of ways to write code. There&#8217;s no wrong or right, there&#8217;s only what is appropriate for your application. But when you&#8217;ve decided which way to go, stick with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inheritance in Javascript</title>
		<link>http://coffeescripter.com/2010/07/inheritance-in-javascript/</link>
		<comments>http://coffeescripter.com/2010/07/inheritance-in-javascript/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 08:36:10 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=167</guid>
		<description><![CDATA[Javascript is a very dynamic language, and you can implement inheritance and code reuse in multiple ways. Lately, I&#8217;ve grown fond of what Douglas Crockford calls Parasitic Inheritance.
By using parasitic inheritance, you can avoid using the new operator all together. The new operator isn&#8217;t evil, but it&#8217;s problematic in that if you write a function [...]]]></description>
			<content:encoded><![CDATA[<p>Javascript is a very dynamic language, and you can implement inheritance and code reuse in multiple ways. Lately, I&#8217;ve grown fond of what Douglas Crockford calls <a href="http://www.crockford.com/javascript/inheritance.html">Parasitic Inheritance</a>.</p>
<p>By using parasitic inheritance, you can avoid using the new operator all together. The new operator isn&#8217;t evil, but it&#8217;s problematic in that if you write a function and you expect it to be called with the new operator but someone forgets it, wild thing can happen, and it can be really hard to debug. Let&#8217;s take an example:</p>
<pre class="brush: jscript;">
function greet() {
  alert(&quot;Welcome, everyone!&quot;);
}
function Greeter(name) {
  this.name = name;
}
Greeter.prototype.greet = function() {
  alert(&quot;Welcome &quot; + this.name);
}
function Person(name) {
  this.name = name;
  this.greet();
  return this;
}
Person.prototype = new Greeter();
Person.prototype.toString = function() {
  return &quot;I am &quot; + this.name;
}

// Example 1
var name = &quot;Andy&quot;;
var person = new Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;

// Example 2
var name = &quot;Andy&quot;;
var person = Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Andy&quot;
alert(name); // alerts &quot;Coffeescripter&quot;
</pre>
<p><em>This way of writing a class and saying that Person inherits from Greeter is rather ugly, so check out John Resigs implementation for some eye candy: <a href="http://ejohn.org/blog/simple-javascript-inheritance/">http://ejohn.org/blog/simple-javascript-inheritance/</a></em></p>
<p>If you&#8217;re not familiar with how <code>this</code> works in Javascript, this may blow your mind. But it&#8217;s perfectly valid code, it&#8217;s just that the <code>this</code> variable points to different places depending on whether you used the new operator or not. When the new operator is used, <code>this</code> points to the new instance that was created. When you&#8217;re not using the new operator, <code>this</code> points to the object that the function was executed in, which in this case was the window object, and that is why <code>this.name = name</code> is overriding the value of the global variable <code>name</code>. This because <code>var name = "Andy";</code> here is technically the same as <code>window.name = "Andy";</code>.</p>
<p>You can&#8217;t tell from inside the function if the new operator was used or not, so you can&#8217;t throw an exception if the new operator was omitted. You could just say that &#8220;all functions that begin with a capital letter should be called with the new operator, or else you&#8217;re stupid&#8221; and be done with it. And while that might be true, you&#8217;re still going to be the one debugging for an hour or so when the new guy who doesn&#8217;t know Javascript that well forgets about the new operator.</p>
<h2>Parasitic Inheritance</h2>
<p>So how about that parasitic inheritance then? It works like this instead:</p>
<pre class="brush: jscript;">
var Greeter = function(name) {
  return {
    greet: function() {
      alert(&quot;Welcome &quot; + name);
    }
  };
};
function Person(name) {
  var obj = Greeter(name);
  obj.greet();
  obj.toString = function() {
    return &quot;I am &quot; + name;
  }
  return obj;
}

// Example 1
var name = &quot;Andy&quot;;
var person = new Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;

// Example 2
var name = &quot;Andy&quot;;
var person = Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;
</pre>
<p>The behaviour is the same if you call Person with the new operator or not. And because of that, it simpler just to forget about the new operator. To me, this code is more straight forward and less magical than the first example, which is always a good thing. One issue people is having with this approach is that for every Person you create, you also create new versions of the greet and toString functions. With the first example, all Person objects share the exact same greet function. That of course means less memory usage, but it also introduces a somewhat scary thought. If all Person objects share the same greet function, what happens when someone decide to replace a persons greet function, it doesn&#8217;t just affect that object, it affects all person objects.</p>
<h2>This trouble with parasitic inheritance</h2>
<p>Something I kept running into with parasitic inheritance was how I didn&#8217;t have access to the created object in the beginning of the function, like this:</p>
<pre class="brush: jscript;">
function Person() {
  var bazooka = Bazooka(this);
  return {
    shoot: function() {
      bazooka.shoot();
    }
  };
}

var Bazooka = function(parent) {
  return {
    shoot: function() {

    }
  }
}
</pre>
<p>Disregarding that we have a cyclic reference here between Person and Bazooka, the problem is that <code>this</code> in <code>var bazooka = Bazooka(this);</code> isn&#8217;t pointing to the person object that we are creating, but the object that the Person function is running in; the window object. So how do we get around this? We could do something like:</p>
<pre class="brush: jscript;">
function Person() {
  var obj = {
    shoot: function() {
      bazooka.shoot();
    }
  };
  var bazooka = Bazooka(obj);
  return obj;
}
</pre>
<p>But that&#8217;s about as pretty and clear as VB&#8217;s let&#8217;s-use-a-variable-with-the-same-name-as-the-function-as-the-return-mechanism-because-function-names-never-change-and-nobody-will-forget-to-update-all-references-to-the-return-variable-when-the-function-is-renamed. So yeah, we can do better. Something like this:</p>
<pre class="brush: jscript;">
function Person() {
  var bazooka;
  return {
    _init: function() {
      bazooka = Bazooka(this);
      return this;
    },
    shoot: function() {
      bazooka.shoot();
    }
  }._init();
}
</pre>
<p>It looks a lot better, and if you&#8217;re used to classical inheritance, you&#8217;re probably used to looking for property declarations at the top, a constructor right after that, and methods down below. If you&#8217;re the suspicious type, you might have noticed that by doing this, we are exposing the <code>_init</code> function to be called again. Which is true, there is nothing stopping you from doing: <code>var p = Person(); p._init();</code> But if this means the end of the world for you, you can always add <code>this._init = undefined;</code> as the first line in the _init function, which makes it impossible to call it twice. </p>
<h3>Privileged functions</h3>
<p>In the first example, there is no way to have a private function that all your public functions can call, not even with John Resigs prettier version. But with parasitic inheritance, it&#8217;s very natural to hide variables and functions through closures, like this:</p>
<pre class="brush: jscript;">
function Person(name) {
  var bazooka;
  var greet = function() {
    alert(&quot;Hi! I'm &quot; + name);
  };
  return {
    _init: function() {
      bazooka = Bazooka(this);
      if(name == &quot;Andy&quot;) {
        greet();
      }
      return this;
    },
    shoot: function() {
      if(name != &quot;Andy&quot;) {
        bazooka.shoot(name);
      }
    }
  }._init();
}
</pre>
<p>Through the closure that the function call to Person creates, both shoot and _init has access to greet, bazooka and name.</p>
<h2>Conclusion</h2>
<p>The key difference between classical and parasitic inheritance is that the classical way is much more focused on an objects type. Change one object, and all other objects of that same type get&#8217;s changes. Parasitic inheritance doesn&#8217;t care about types. It&#8217;s more about assembling functions and properties to create a logical unit. Instead of caring if an argument to your function is of the type Person, you only care about whether or not it has the function greet. There is no right or wrong here, and the two can happily co-exists, but the thing that makes me use parasitic inheritance is how it&#8217;s aligned with the dynamic nature of Javascript. </p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2010/07/inheritance-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Javascript OO gotcha</title>
		<link>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/</link>
		<comments>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 18:01:57 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=138</guid>
		<description><![CDATA[Every now and then I run into this issue when I&#8217;m do OO in Javascript. It creates really wierd bugs that can make you want to rip you hair off (I have no hair left&#8230;), so I thought it might be a good idea to share it. It all boils down to the fact that [...]]]></description>
			<content:encoded><![CDATA[<p>Every now and then I run into this issue when I&#8217;m do OO in Javascript. It creates really wierd bugs that can make you want to rip you hair off (I have no hair left&#8230;), so I thought it might be a good idea to share it. It all boils down to the fact that objects in Javascript are references by default.</p>
<p>So let&#8217;s say you have code like this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name) {
    this._name = name;
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});

var fred = new User('Fred');
var mike = new User('Mike');
var jennifer = new User('Jennifer');
var sara = new User('Sara');

fred.addFriend(jennifer.name());
fred.addFriend(sara.name());

mike.greetFriends();
</pre>
<p>You would expect that Mike who nobody seems to like would just alert &#8220;Hi !&#8221;, but he alerts Freds friends as well. And that&#8217;s because objects in Javascript (arrays are objects as well) are passed by reference. So all of Freds friends also become Mikes friends, since they share the same friend array.</p>
<p>So to get away from this, the trick is to declare your properties in the constructor, like this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name) {
    this._name = name;
    this._friends = [];
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});
</pre>
<p>Since the constructor (init) is called every time a new user object is created, the friends array is set for only that instance. But sometimes you might forget to reset the variable in the constructor, so I usually do this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: false,
  _name: '',
  init: function(name) {
    this._name = name;
    this._friends = [];
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});
</pre>
<p>Just to make sure that there&#8217;s no risk of a shared array. You might even skip the declaration at the top, but I&#8217;m used to looking there for property declarations, so I set them at the top. </p>
<p>I&#8217;m sure that you already thought about this by know, but this feature in Javascript makes it possible to have &#8220;static&#8221; properties that are shared between all instances of the same class. I would advise you to use such a strategy sparsely though, as it&#8217;s not very obvious that it&#8217;s a shared variable. But the good thing about it is that this Javascript version of static properties doesn&#8217;t suffer the same problems that statics do in Java/PHP, since the static can be turned into a local just by resetting it in the constructor, without it affecting other objects. Something like:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name, share_friends) {
    this._name = name;
    if(!share_friends) {
      this._friends = [];
    }
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});

var fred = new User('Fred', true);
var mike = new User('Mike', false);
var jennifer = new User('Jennifer', true);
var sara = new User('Sara', true);

fred.addFriend(jennifer.name());
fred.addFriend(sara.name());
mike.addFriend(fred.name());

mike.greetFriends();
sara.greetFriends();
</pre>
<p>This code now tells us that Mike only has Fred as a friend, whereas Sara shares friends with Fred, and has both herself and Jennifer as her friends.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Building a Javascript clone of Civilization, part 1</title>
		<link>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/</link>
		<comments>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 07:08:28 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=45</guid>
		<description><![CDATA[So I thought it might be fun to build a game in Javascript, and not just some dead simple game. As I was younger (because I&#8217;m so old now) I liked the games Civilization and Colonization a lot, so I wanted to try to make a clone of them, using Javascript.
I decided from the start [...]]]></description>
			<content:encoded><![CDATA[<p>So I thought it might be fun to build a game in Javascript, and not just some dead simple game. As I was younger (because I&#8217;m so old now) I liked the games Civilization and Colonization a lot, so I wanted to try to make a clone of them, using Javascript.</p>
<p>I decided from the start that I wanted to use jQuery, and Object Oriented Javascript. To mimic OO inheritance, I once again used John Resigs <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a>.</p>
<p>So the first thing to do was to model the entities I needed in the game. I started out with the obvious one, the Unit class. Added a few methods to it, and moved on to the Map class, because I wanted to get something at least partially working very fast. So I made a Map class that generated a map of tiles that could hold units. I greated a Tile class, and the Map class would hold all instances to the tiles. A tile has a &#8220;height&#8221; property, which defines the altitude of it (1 is deep water, 6 is low land, and 10 is oh-my-god-that&#8217;s-high-mountains). For now, I&#8217;m just randomizing the heights of the generated tiles, but that doesn&#8217;t make a very realistic map, so that&#8217;s on my TODO-list.</p>
<p>To get something working, I needed a way to connect unit to tiles. At first, I thought about letting the Unit hold an instance to the Tile it was on, but soon realized that it wouldn&#8217;t be a good idea. Instead, I created a UnitLocations class, which holds all units and all tiles, and connects them. </p>
<p>I also needed to be sure that units can&#8217;t move over the map as they like, land units can move over water (except the JesusUnit, which will be covered in part 23 of this series). So I created a LandUnit, and a WaterUnit, derived from the Unit base class. For now, when you try to move a unit, the <code>game.Tile::canTake(game.Unit unit)</code> method is queried to see if the unit can be moved to that tile. I&#8217;m pretty sure I have to move that logic to somewhere else at a later stage, but it&#8217;s good enough for now.</p>
<p>So I had a map, and I had a couple of units on it, that could move around. Then I remembered that Civilization is turn based. And my ambition is to let players play against each other over the series of tubes that we call the Internets. But sitting and waiting for other players to make their move can be tiring at best, so I needed another solution. Instead, i decided that Units has a &#8220;move_points&#8221;. Let&#8217;s say that LandUnit has 3 move_points, and moves over three tiles. Then move_points becomes zero, and that unit has to rest for a couple of seconds before it can move again. Right now, it&#8217;s accomplished by an interval running in every unit that adds move_points every two seconds. Each unit type also has a &#8220;max_move_points&#8221; property, so you wouldn&#8217;t be able to move the unit over a gazillion tiles if you waited long enough.</p>
<p>So I was quite excited about this, and wanted to move on and make more features. But then I stopped and thought some more about it, and realized that I need an event architecture to move on. And I hear you, Javascript already has events, and jQuery allows you to trigger custom events that you define on your own, but I wasn&#8217;t quite satisfied with how that worked. So I&#8217;m going to get cracking on a way to define and trigger my own events, and that will be part 2 of this series.</p>
<p>You can find the game here for now: <a href="http://dev.online.nu/game/" target="_blank">http://dev.online.nu/game/</a>.<br />
When you want to move a unit (a unit is one of those pretty red squares), just click on it, then move it by using your keyboard arrows.</p>
<p>Til then, happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Automatic getters and setters in Javascript</title>
		<link>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/</link>
		<comments>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 18:18:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=1</guid>
		<description><![CDATA[When you&#8217;re working with object oriented code, writing those dumb getters and setters can be a bit of a pain, since they&#8217;re just getting and setting simple values most of the times. So I thought I&#8217;d bring in some magic to my Javascript classes to generate these methods.
I&#8217;m using John Resigs Simple Javascript Inheritance to [...]]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re working with object oriented code, writing those dumb getters and setters can be a bit of a pain, since they&#8217;re just getting and setting simple values most of the times. So I thought I&#8217;d bring in some magic to my Javascript classes to generate these methods.</p>
<p>I&#8217;m using John Resigs <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a> to emulate class inheritance in Javascript, so you might want to check that out.</p>
<p>So the first step is to create a base class that takes care of the getters and setters for us.</p>
<pre class="brush: jscript;">
var DomainObject = Class.extend({
  init: function() {
    /**
     * Generating getters and setters for the domain object by looping over
     * all properties that start with _ and automatically creating getters/setters
     * If the property is &quot;_first_name&quot;, the getter will become &quot;firstName()&quot;, and
     * the setter will become &quot;setFirstName()&quot;
     */
    for(var key in this) {
      createGettersAndSetters(key, this);
    }
    function camelize(str) {
      var ret = '';
      for(var i = 0; i &lt; str.length; i++) {
        var chr = str.charAt(i);
        if(chr != '_') {
          ret += chr;
        } else {
          i++;
          ret += str.charAt(i).toUpperCase();
        }
      }
      return ret;
    }
    function createGettersAndSetters(key, context) {
      if(key.indexOf('_') === 0 &amp;&amp; typeof context[key] != 'function') {
        var set_method = 'set'+ camelize(key);
        // Make sure we don't override an existing setter
        if(!context[set_method]) {
          context[set_method] = function(value) {
            context[key] = value;
          }
        }
        // Using substr to remove the starting _, since we don't want the
        // string to start with a capital letter, as we do with the setters
        var get_method = camelize(key.substr(1));
        // Make sure we don't override an existing getter
        if(!context[get_method]) {
          context[get_method] = function() {
            return context[key];
          }
        }
      }
    }
  }
});
</pre>
<p>So now that we&#8217;ve got our class that handles the magic, we need to test it!</p>
<pre class="brush: jscript;">
var User = DomainObject.extend({
  _id: false,
  _name: '',
  setId: function(id) {
    if(validUserId(id) {
      this._id = id;
    }
  },
  sayHello: function() {
    alert('Hi! My name is '+ this.name());
  }
});

var usr = new User();
usr.setName('Anders');
// Will alert &quot;Hi! My name is Anders&quot;
usr.sayHello();
</pre>
<p>So what is does is that it takes all properties of the &#8220;class&#8221; that begins with an underscore, and generates getters and setters for them, if a getter/setter isn&#8217;t already defined. The format for the methods are setProperty() and property(), so if you have a property called &#8220;_first_name&#8221;, the setter becomes &#8220;setFirstName&#8221;, and the getter becomes &#8220;firstName&#8221;.</p>
<p>Happy coding! </p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
