Last active
September 30, 2016 17:08
-
-
Save ozzieperez/fd93281b0a9b4067b3cc4bdb28ed90bb to your computer and use it in GitHub Desktop.
Add all constructor parameters for a JS class to "this" automatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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