Self-modifying Javascript objects

I thought it’d be interesting to consider Javascript objects which can modify their own behavior over time. A use case for this (what I’m doing) is pages of data, where data is first looked up, then cached in memory, then cleared. A simple case (demonstrated below) is memoization.

The following query will do an ajax lookup of some data:

function loadData() {
  var data;

    url: "blocks/" + this.block,
    async: false
  }).done(function(blockData) {
    data = blockData.split("\n")
    for (var i = 0; i < data.length; i++) {
      data[i] = data[i].split("\t")

  return data;

var x = {block: 'xabnh', getData: loadData}


This shows how one might trigger caching the results. Once retrieved, the cached data is hidden within a closure, and the mechanism for retrieving data is updated. In the case of a memory manager, these pages are later cleared out by replacing the memoization function with a third function, which starts the process all over again.

var x = {block: 'xabnh', getData: memoize(loadData)}

function memoize(getData) {
  return function() {
    var data = getData.apply(this);
    function savedData() {
      return data;
    this.getData = savedData;
    return data;


There are a few downsides to this approach; data in the closure is hidden from inspection, the current state of the object is hidden, and can change quickly. A generalized approach to this problem might pass an object into the getData function to show state or trigger a debug mode.

2 Replies to “Self-modifying Javascript objects”

  1. agreed, I used to do things similar to this if I needed to do some setup the first time a function was called. For example;

    var obj = {
    getCount: function() {
    var count = 0;
    this.getCount = function() {
    return ++count;
    return count;

    Also useful if you want to setup some defaults, saves an if statement every time the function is called. I try to stay away from things like this now though as I use an Aspect Oriented ( approach which decorates the function and replacing the function means I’ll lose the decoration

Leave a Reply

Your email address will not be published. Required fields are marked *