How to use both static and instance methods in Javascript

I have such a design in PHP (similar to Eloquent ORM):

class User {
    private $id;
    private $name;

    public __constructor($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    static function getUser($id) {
        //get data from database
        return new User($id, 'Adam');
    }
}

I use it as follows:

$user = User::getUser(1);

Now I want to do this in Javascript. I got to this:

var User = function(id, name) {
    this.id = id;
    this.name = name;
}

User.prototype.getName = function() {
    return this.name;
}

How to add a static function?

How do I call it so that it returns an instance of the object?

Does this design pattern have a name?


UPDATE:

Short answer to my question:

User.getUser = function(id) {
    //get data from database
    return new User(id, 'Adam');
}
+4
source share
1 answer

How to add a static function?

With ES5 you should use:

User.staticMethod = function (user, name) {
  user.name = name;
}

How do I call it so that it returns an instance of the object?

User.staticMethod = function (id, name) {
  return new User(id, name);
}

Does this design pattern have a name?

This is a factory method .

How can I use ES6 to make it more concise?

With classes!

class User {
  static createUser(id, name) {
    return new User(id, name);
  }

  constructor(id, name) {
    this.id = id;
    this.name = name;
  }

  get name() {
    return this.name;
  }
}
+4
source

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


All Articles