0

code 1

var User1 = function (name, age) {
    this.name = name;
}
User1.prototype.getName = () => { return this.name; }
var x = new User1("gladiator");
console.log(x.getName());

Output = undefined

code 2

var User1 = function (name, age) {
    this.name = name;
}
User1.prototype.getName = function () { return this.name; }
var x = new User1("gladiator");
console.log(x.getName());

Output = gladiator

  • FWIW, the modern way to write that in JavaScript would be `class User1 { constructor(name, age) { this.name = name; this.age = age; } getName() { return this.name; } }` More in my answer [here](https://stackoverflow.com/a/30783368/157247). – T.J. Crowder Dec 30 '21 at 08:48
  • 1
    Answering the question: The only difference is that `getName` refers to an arrow function in the first case and a traditional function in the second case. Since arrow functions close over `this`, that means `this` when you call `getName` is whatever it was where you defined the function; it doesn't get set by how you call it as in the second case. – T.J. Crowder Dec 30 '21 at 08:51

0 Answers0