我在PHP中有这种设计(类似于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');
}
}
我是这样使用它的:
$user = User::getUser(1);
现在,我想用Javascript来做这件事。我走到了这一步:
var User = function(id, name) {
this.id = id;
this.name = name;
}
User.prototype.getName = function() {
return this.name;
}
如何添加静态函数?
如何调用它以使其返回实例化的对象?
此设计模式有名称吗?
更新:
对我问题的简短回答是:
User.getUser = function(id) {
//get data from database
return new User(id, 'Adam');
}
使用如何添加静态函数?
ES5,您将使用:
User.staticMethod = function (user, name) {
user.name = name;
}
如何调用它以使其返回实例化的对象?
User.staticMethod = function (id, name) {
return new User(id, name);
}
此设计模式有名称吗?
这是一种工厂方法。
如何使用 ES6 使其更简洁?
有课!
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;
}
}