I'm trying to figure out a one-liner code using map.
Here is a simple set up.
function Cat(name) {
this.name = name;
// FYI: using __proto__ is discouraged. thanks @KarelG
this.__proto__.mew = function () {
console.log(this.name + " mews");
};
}
var cats = [
new Cat('MB'),
new Cat('503')
];
Then, I can use map() to call mew method in cats.
cats.map(function (cat) {
cat.mew();
});
// MB mews
// 503 mews
call() on prototype also works.
cats.map(function (cat) {
Cat.prototype.mew.call(cat);
});
// MB mews
// 503 mews
And here is my final one-liner, but it emits error and I could't understand why:
cats.map(Cat.prototype.mew.call);
// Uncaught TypeError: undefined is not a function
// at Array.map (<anonymous>)
Checking typeof Cat.prototype.mew.call says it's a function
and map()'s parameter should be a function.
Could anyone explain why it doesn't work? What did I miss and where to correct?
cats.map((Cat) => Cat.mew.call());or likecats.map(function(Cat) { Cat.mew.call()});[[Prototype]]using__proto__is discouraged (mainly due of the nature of prototypes which may impact the performance). Even if there is a function in favor of that__proto__(the function isObject.setPrototypeOf()), I should not use it.