A Javascript prototype question

I am currently learning on how to use prototype in JS.
I am curious about what happened after I extended a prototype and then I store the function as variable. why the console.log gives me a Window object for the canvas? Why don’t I just get the empty function object i just created?

Here is the code:

var img = loadImage("/idle.png");
var s = img.splitter();
console.log(s);

p5.Image.prototype.splitter = () => {
  // some irrelevant codes here
  return this;
}
/** The output in short:
Window {close: function close(), stop: function stop(), focus: function focus(), blur: function blur(), open: function open()…}
*/

Thanks.

Oh. I found an answer here:

Never mind.

As you’ve already found out just now, creating a function via => syntax binds its this permanently to its current context at creation time:

But method functions need to have their this to be the current object which had invoked it at call time:

p5.Image.prototype.splitter = function () {

1 Like

Good answer as always. Thanks. :innocent:

For the completeness of this thread:
The answer I provide is outdated now. We don’t need var that = this; to let this refer to the object now. My mistake was to use the “=>” instead of the function().

1 Like