Closed giper45 closed 7 years ago
arrow functions are some kind special. They are bound to their outside context and cannot be bound to your stamp instance.
Don't use fat arrow function with init method.
Thanks @amelon ! I'll put some code examples for @giper45
const outerObject = {
name: "outerObject",
f1: function() { // <---------- regular function
console.log(this);
const innerObject = {
name: "innerObject",
f2: () => { // <---------- arrow function
console.log(this);
}
};
innerObject.f2();
}
};
outerObject.f1();
The code above will print:
{ name: 'outerObject', f1: [Function: f1] }
{ name: 'outerObject', f1: [Function: f1] }
It prints the same object! Why? Because arrow functions (f2
) INHERIT the this
context of the running function (f1
).
There is a way to use arrow functions as initializers. Here it is:
const Availability2 = stampit().init((_, {instance}) => {
instance.open = function open() { }; // See this `instance` variable?
// ...
});
If any questions feel free to ask.
Thanks very much for the explanation !!! I've learned something more about Javascript in general :) !
Thanks for this wonderful library ! Just I little question (for curiosity), why when I use arrow function notation in init function it gives empty object on instantiation ? I.e with normal notation:
while the arrow notation gives this :
Thanks !