How to force use of JavaScript constructor?

I have the following constructor:

function Person(name, age) {
  this.name = name;
  this.age  = age;
}

Now if I say:

var p = new Person("jon", 25);

It will create an instance Person, but what if the user does the following:

var p = Person("jon", 25);

This will lead to the definition nameand ageobject window.

My question is, is there a way to prevent the user from calling directly Personwithout newand thus prevent the addition of an object window?

+4
source share
4 answers

Here's the path around it using the safe area constructor:

function Person(name, age) {
  if (this instanceof Person) {
    this.name = name;
    this.age = age;
  } 
  else {
    return new Person(name ,age);
  }
}

Read more: New / Scope of safe constructors in JavaScript OO

+3
source

You can explicitly check the condition:

function Person(name, age) {
  if (!this || this === window)
    return new Person(name, age);
  this.name = name;
  this.age = age;
}

- -

var obj = {};
Person.call(obj, "John", 22);

instanceof, , :

function Person(name, age) {
  if (!(this instanceof Person))
    return new Person(name, age);
  this.name = name;
  this.age = age;
}
+2

. JavaScript ?

new, new .


, (.. "" new), ES6 :

class Person {
  constructor() {
    // ...
  }
}

, class, new. .

+1
function Person(name ,age){
    if ( ! (this instanceof Person) ) {
        return new Person(name, age);
    }
    this.name = name;
    this.age  = age;
}
0

Source: https://habr.com/ru/post/1614757/


All Articles