Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:13
Show Gist options
  • Save laser/38879129fdd6a10e7466 to your computer and use it in GitHub Desktop.
Save laser/38879129fdd6a10e7466 to your computer and use it in GitHub Desktop.
createMethod

Creating Methods in JavaScript

Creating a (named) method on an object is typically done with an anonymous function expression, e.g.:

$scope.updateWarningLevel = function(warningLevel) {
  $scope.worksheet.warningLevel = warningLevel;
}

...but that means that if your updateWarningLevel method blows up, your stack trace will be hard to read as the function was anonymous.

Folks get around that by naming both the property and function expression, like:

$scope.updateWarningLevel = function updateWarningLevel(warningLevel) {
  $scope.worksheet.warningLevel = warningLevel;
}

...which is lame because you just duplicated the name. You also just opened yourself to accidentally renaming the property and not reflecting that change in the name of the function expression.

Good news is that you can get around that shizzle by parsing the name out of a function expression and using that to add a property / value to an object:

function getFunctionName(fun) {
  var name = fun.toString();
  name = name.substr('function '.length);
  name = name.substr(0, name.indexOf('('));
  return name === '' ? undefined : name;
}
    
function addMethod(o, f) {
  o[getFunctionName(f)] = f;
}

...which you can then use to do:

addMethod($scope, function updateWarningLevel(warningLevel) {
  $scope.worksheet.warningLevel = warningLevel;
});

so that your stack traces don't suck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment