Skip to content

Instantly share code, notes, and snippets.

@Hebilicious
Created January 22, 2018 00:51
Show Gist options
  • Save Hebilicious/51b77ce6f7efb1a1b1c3daf9b7288201 to your computer and use it in GitHub Desktop.
Save Hebilicious/51b77ce6f7efb1a1b1c3daf9b7288201 to your computer and use it in GitHub Desktop.
ES Class constructor spread operator arguments
//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()
@aguevara
Copy link

aguevara commented Jun 22, 2020

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 maybe this.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 of this. Your line 17 would be less complicated if that were possible, you could then just write this.what = ...stuff. I was hoping for something like this = {...this, ...stuff} but doesn't work because you cannot assign to this.

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