Skip to content

Instantly share code, notes, and snippets.

@ozzieperez
Last active September 30, 2016 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzieperez/fd93281b0a9b4067b3cc4bdb28ed90bb to your computer and use it in GitHub Desktop.
Save ozzieperez/fd93281b0a9b4067b3cc4bdb28ed90bb to your computer and use it in GitHub Desktop.
Add all constructor parameters for a JS class to "this" automatically
<html>
<head>
<script>
"use strict";
class BaseClass {
//Adds the parameters of a method to the context (this)
addParametersToThis() {
var parameters = this.getFunctionParameterNames(this.constructor);
for (var i = 0; i < parameters.length; i++) {
this[parameters[i]] = arguments[i];
}
}
//Gets the names of the parameters of a method
getFunctionParameterNames(func) {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
ARGUMENT_NAMES = /([^\s,]+)/g,
fnStr = func.toString().replace(STRIP_COMMENTS, ''),
result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
return result === null ? [] : result;
}
}
class MyClass extends BaseClass {
constructor(arg1, arg2) {
super();
//THIS IS THE MONEY SHOT!
this.addParametersToThis.apply(this, arguments);
//CONFIRM IT ADDED IT TO "this"
console.log("Did it work: " + JSON.stringify(this.arg2));
}
}
//TEST IT
var hello = "1",
sweet = {nice:3};
var myClass = new MyClass(hello, sweet);
</script>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment