Search code examples
javascriptprototypeq

"this" inside prototype takes window instead of object


I created an Object called Survey and added a prototype function to it, and when I console log this inside the prototype function the log shows window object instead of parent Survey Object.

function Survey(questions = []) {
  this.__questions__ = questions;
};
Survey.prototype.testFunction = () => {
  console.log(this);
  return this.__questions__;
}
// Create your object here
const SUR = new Survey(['1','2']);

SUR.testFunction(); // this prints [[Window]] Object instead of Survey

Expected result would be Survey object


Solution

  • It is because you used an Arrow function. In arrow function, this will be reference to outside. Just use a normal function instead.

    Survey.prototype.testFunction = function() {
      console.log(this);
      return this.__questions__;
    }