I am trying to do the following:
- Create a constructor function
- Create a function and store it as a variable (the function will rely on value of
this
) - Attach the function to the prototype of the constructor function
I can't figure out how to keep value of this
inside the function to be pointing to the instance.
This code is from ChatGPT and explains exactly what I want to do:
let myFunction = () => {
console.log(this.value);
};
function MyObject(value) {
this.value = value;
}
MyObject.prototype.showValue = myFunction;
BUT I either don't know how to use it or it straight up doesn't work as it suppose to.
The test I ran:
a = new MyObject('a')
b = new MyObject('b')
a.showValue() // I am expecting `a` to be printed out, but undefined is printed
b.showValue() // I am expecting `b` to be printed out, but undefined is printed
So what's happening here? Why is this
not pointing to the instance? How do I go about fixing this?