0

Scenario (1)

var jk = function(name,age,lastanme){
    this.name = name;
    this.age = age;
    this.lastanme = lastanme; 

}

var op = new jk("ravi",45,"kumar");
console.log(op);

Scenario (2)

var jk = (name,age,lastanme)=>{
    this.name = name;
    this.age = age;
    this.lastanme = lastanme; 

}

var op = new jk("santhosh",45,"kumar");
console.log(op);

*const op = new jk("sandy",56,"kumar"); ^

TypeError: jk is not a constructor

Why is the second program with the arrow function giving the error 'jk is not a constructor'?

donatJ
  • 3,105
  • 3
  • 32
  • 51

2 Answers2

0

Whenever I get stuck, I tried to take a look at the docs, for javascript, you can use mozilla mdn web docs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

What you're tryin to do is using arrow function as a constructor, here in the docs they clearly stated

Arrow functions cannot be used as constructors and will throw an error when used with new.

So instead, what you want is

var jk = (name,age,lastanme)=>{
    this.name = name;
    this.age = age;
    this.lastanme = lastanme; 

}

var op = jk("santhosh",45,"kumar");
console.log(op);
ThatBuffDude
  • 451
  • 4
  • 11
0

new keyword is used to create object instances of classes. And in Javascript, it returns plain Javascript objects. It cannot be used with arrow functions.

In this case you should call the function directly. Try the following

var op = jk("santhosh",45,"kumar");
ruth
  • 29,535
  • 4
  • 30
  • 57