JavaScript – Define If Undefined

 


There have been many times when I needed a way to define a function (or variable) only if it wasn’t already defined. Since this seems to be such a common situation, I decided to write a function which will only define a variable, in a given namespace if a definition doesn’t already exist:

function define(name, definition) {
  var ret = {}, context = this;
  name = name.split(".");
  for(var i = 0, z = name.length - 1; i <= z; i++) {
    context = typeof context[name[i]] == "undefined"
      ? context[name[i]] = (i == z ? definition : {})
      : context[name[i]];
  }
  return context === definition;
}

The above define() takes two parameters. The first parameter is the namespace that will be defined if it hasn’t already been defined. The second parameter is the object or primitive that will be defined. The returned value is a boolean indicating true if the specified variable was defined. The following is an example of how to use this function:

// Display:  "jStuff is undefined."
alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined.");

define("jStuff.alert", function(msg) {
  alert(msg);
  return msg;
});

// Display:  "jStuff is defined."
alert("jStuff is " + (typeof jStuff == "undefined" ? "un" : "") + "defined.");

// Display and store:  "Show and save this message."
var str = jStuff.alert("Show and save this message.");

As you may have noticed by the function definition, you can even use the apply() or call() function on this function to bind the starting context (which defaults to the global object). I am definitely thinking that this is jPaq material. 8)

 

Leave a Reply

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


5 + four =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">