Mihai Răducanu
Mihai Răducanu

Reputation: 12585

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');
}

Upvotes: 5

Views: 191

Answers (1)

ssube
ssube

Reputation: 48257

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;
  }
}

Upvotes: 4

Related Questions