X.prototype.y called on incompatible type

Our volunteers haven't translated this article into Ελληνικά yet. Join us and help get the job done!
You can also read the article in English (US).

Message

TypeError: 'this' is not a Set object (EdgE)
TypeError: Function.prototype.toString called on incompatible object (Firefox)
TypeError: Function.prototype.bind called on incompatible target (Firefox)
TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
TypeError: Bind must be called on a function (Chrome)

Error type

TypeError

What went wrong?

When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function.

This issue can arise when using the Function.prototype.call() or Function.prototype.apply() methods, and providing a this argument which does not have the expected type.

This issue can also happen when providing a function (stored in an object) as an argument to another function. In this case, the object won't the this target of the function. To work-around this issue, you will either need to provide a lambda which is making the call, or use the Function.prototype.bind() function to force the this argument to the expected object.

Examples

Invalid cases

var mySet = new Set;
['bar', 'baz'].forEach(mySet.add);
// mySet.add is a function, but "mySet" is not captured as this.

var myFun = function () {
  console.log(this);
};
['bar', 'baz'].forEach(myFun.bind);
// myFun.bind is a function, but "myFun" is not captured as this.

Valid cases

var mySet = new Set;
['bar', 'baz'].forEach(mySet.add.bind(mySet));
// This works due to binding "mySet" as this.

var myFun = function () {
  console.log(this);
};
['bar', 'baz'].forEach(x => myFun.bind(x));
// This works using the "bind" function. It creates a lambda forwarding the argument.

See also

Εθελοντές και ετικέτες εγγράφου

Ετικέτες: 
Συνεισφέροντες σε αυτή τη σελίδα: PatrickKettner, WangNianyi2001, fscholz, nbp
Τελευταία ενημέρωση από: PatrickKettner,