Created
January 22, 2018 00:51
-
-
Save Hebilicious/51b77ce6f7efb1a1b1c3daf9b7288201 to your computer and use it in GitHub Desktop.
ES Class constructor spread operator arguments
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
//Let's create some arguments as functions | |
let message = () => "hello" | |
let content = () => "world" | |
let text = () => "lorem" | |
//Let's change the function internal name value... | |
Object.defineProperty(text, "name", {writable:true}); | |
text.name = "book" | |
//Now we create a class | |
//Arguments needs to be a function with a name and a return value. | |
class SmartClass { | |
//Use spread to catch every arguments... | |
constructor(...stuff) { | |
console.log(stuff) // 0 indexed array with our functions as value | |
console.log(arguments) // Object | |
this.what = Object.entries(arguments).map(([key, arg], i) => this[arg.name] = arg()) | |
} | |
logArgs (){ | |
console.log(this.message) // "Hello" | |
console.log(this.content) // "World" | |
console.log(this.text) // undefined | |
console.log(this.book) // "lorem" | |
console.log(this.what) // ["hello", "world", "lorem"] | |
} | |
} | |
let smart = new SmartClass(message, content, text) | |
smart.logArgs() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. I was looking for a way to use spread to copy the properties from an object passed in to a constructor to
this
. Seems it is not possible to do that. Your line 17 made me think maybethis.what
was some kind of magic javascript property that would allow me to assign to it using spread and have all the properties from the object magically get added to the prototype ofthis
. Your line 17 would be less complicated if that were possible, you could then just writethis.what = ...stuff
. I was hoping for something likethis = {...this, ...stuff}
but doesn't work because you cannot assign tothis
.