Mihai Răducanu Mihai Răducanu - 7 months ago 13
PHP Question

How to have both static and instance methods in Javascript

I have this kind of 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 like this:

$user = User::getUser(1);


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

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

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


How do I add the static function?

How do I call it so that it returns an instantiated object?

Does this design pattern have a name?




UPDATE:

The short answer to my question is:

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

Answer

How do I add the static function?

With ES5, you would use:

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

How do I call it so that it returns an instantiated 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 this 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;
  }
}