ES6 arrow functions not working on the prototype?
Regular function returns a reference to the current JavaScript Object but the arrow function returns the reference to the global window object.
Regular functions are working well with objects using the new keyword. They have the constructor function by which values can be initialized during object creation. It can be managed using the prototype chaining but the arrow function does not have constructor function, prototype chaining. They are not working well with objects. They can not be used with the new keyword for assigning memory.
In your first example, you write your arrow key function inside the regular function, then you will get the output.
function Animal2(name, type){
this.name = name;
this.type = type;
}
Animal2.prototype.toString = function(){
return () => `${this.name} is a ${this.type}`;
}
var myPet2 = new Animal2('Noah', 'cat');
console.log(myPet2.toString()()); //Noah is a cat
Reference: Difference between regular function and arrow key function
Arrow functions provide a lexical this
. It uses the this
that is available at the time the function is evaluated.
It is logically equivalent to (the following isn't valid code since you can't have a variable named this
):
(function(this){
// code that uses "this"
})(this)
In your 1st example the arrow function is within the constructor, and this
points to the newly generated instance.
In your 3rd example, an arrow function isn't used and standard this
behavior works as always (the this in the function scope).
In your 2nd example, you use an arrow function but at the scope it's evaluated, this
is global / undefined.