user5711656
user5711656

Reputation: 3678

how to retrict user to call function with only new operator?

 function person(name){
      if(new.target){
        new throw('Please call with new operator')
      }
      this.name = name

    }

    var a = new person(); // correct wy

    person(); // will give error to user

Can we restrict user to call function with only new .if he call without new operator he will get error I tried like above

can you suggest the better way ?

Upvotes: 0

Views: 44

Answers (1)

Ori Drori
Ori Drori

Reputation: 193037

The problem with your code is that new.target exists only when called with new. The condition should be !new.target:

function Person(name) {
  if (!new.target) throw ('Please call with new operator')
  this.name = name
}

var a = new Person('Moses');

console.log(a);

Person();

Another option is to use an ES6 class. Trying to invoke a class as a function will throw an error:

class Person {
  constructor(name) {
    this.name = name;
  }
}

var a = new Person('Moses');

console.log(a);

Person();

Upvotes: 2

Related Questions