Skip to content

Instantly share code, notes, and snippets.

@keeto
Created April 2, 2010 07:20
Show Gist options
  • Save keeto/352877 to your computer and use it in GitHub Desktop.
Save keeto/352877 to your computer and use it in GitHub Desktop.
Function docStrings in JavaScript
// As a Function method..
(function(){
Function.prototype.docString = function(){
var doc = this[this.toSource ? 'toSource' : 'toString']().match(/['"]\*(.*)\*['"]/);
return (doc) ? doc[1].replace(/^\s+|\s+$/g, '') : '';
};
})();
// Sample Usage:
var func = function(){
'* this is a sample function *';
return 1;
};
console.log(func.docString()) // "this is a sample function"
// With defineProperty/defineGetter..
(function(){
var fnProto = Function.prototype,
docString = function(){
var doc = this[this.toSource ? 'toSource' : 'toString']().match(/['"]\*(.*)\*['"]/);
return (doc) ? doc[1].replace(/^\s+|\s+$/g, '') : '';
};
if (Object.defineProperty) Object.defineProperty(fnProto, 'docString', {get: docString});
else if (fnProto.__defineGetter__) fnProto.__defineGetter__('docString', docString);
else fnProto.docString = '';
})();
// Sample Usage:
var func = function(){
'* this is a sample function *';
return 1;
};
console.log(func.docString) // "this is a sample function"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment