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() |
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
I'm not sure what you're trying to achieve here. What do you mean by inherit one object from another ?
Line 17 is a little bit complicated (refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments), but this.what is an array that contains
["hello", "world", "lorem"]
, which are the values of the 3 functions passed into the constructor.The line also declares class properties with the names of the 3 functions and their values as values.
Now that I look back at this, the readability could be improved.