Starting off I have some object blueprints like this
const blueprints = [
{
"name": "Wizard",
"effect": () => doWizardStuff()
},
{
"name": "Paladin",
"effect": () => doPaladinStuff()
}
]
For now lets assume that the two functions, doWizardStuff() and doPaladinStuff() simply do console.log(this)
Later I create Objects out of the blueprints using Constructors like so:
function Card(fromBlueprint, player){
this.name = fromBlueprint.name
this.effect = fromBlueprint.effect
this.belongsTo = player
}
let myWizard = new Card(blueprints[0],"Player1")
let myPaladin = new Card(blueprints[1],"Player1")
Now I face two problems. First problem is that if I do not wrap the "effect" in blueprints in anonymous function, the assigned function gets executed during execution og new Card(...), which I do not need or want. It however interprests "this" correctly, as the Object which called the function.
{ ...
"effect": doWizardStuff()
...},
{ ...
"effect": () => doPaladinStuff()
...}
let myWizard = new Card(blueprints[0],"Player1")
// Card {name: "wizard", effect: doWizardStuff()}
let myPaladin = new Card(blueprints[1],"Player1")
// doesn't log anything, as doPaladinStuff() doesnt get called during construction
I hope the difference is clear from the example, doWizardStuff() gets called during the construction, while doPaladinStuff() does not, as it is wrapped in anonymous function. Later in the code I can call for it using:
myPaladin.effect() //[object Window]
However, when I call the function this way, "this" logs [object Window] and not the Card {name: "Paladin", effect: () => doPaladinStuff()} which called it. Now my reaserch has led me to believe that .bind or .call may solve this problem, however I havn't figured out how or where to implement them. So to rephrase, my two questions are
So far I have tried many variations of the code but couldnt get a single one to work. I tried using "effect": function() {doPaladinStuff()} instead of arrow functions, passing "this" as an argument, "effect":function() {doPaladinStuff()}.bind(this) and combinations of them all.
So to summerizem my two questions are:
Is there a way to prevent a function from beign called during construction, that does not include wrapping the said function in anonymous function?
if not, how can I pass "this" to the wrapped function, so that it referes to the object which called it and not the Window Object?
Im using vanilla Javascript only.