使用 ES6 类,可以从静态方法 return 实例化 class 吗?
With ES6 Classes, is it ok to return an instantiation of that class from a static method?
class Thing {
constructor(parameter) {
if (parameter) {
this.x = parameter;
}
return this;
}
getX () {
return this.x;
}
static specialThing() {
return new Thing('Special Thing');
}
}
let thingy = Thing.specialThing();
thingy.getX(); // 'Special Thing'
我想在 JavaScript 中执行上述操作(尽管形式更复杂)。当我 运行 这段代码时,它 运行 目前很好,但是我觉得在 class return 中有一个函数 class 的实例化版本感到奇怪。有什么理由不以这种方式构建我的代码吗?
静态方法的替代方法是:
Thing.specialThing = () => {
return new Thing('Special Thing');
};
使用这些东西中的任何一个都有哪些优点和缺点(如果有的话)?还有其他我不知道的更好的方法来实现这个目标吗?
With ES6 Classes, is it ok to return an instantiation of that class
from a static method?
当然,这很好,在某些情况下这是一种公认的做法。当您想将可重用函数编码为可从多个位置调用的可重用函数时,通常会使用它,这是一种调用构造函数和创建对象的特定方式。
名为 specialThing
的静态函数称为工厂函数(一个为您创建并 returns 对象的常规函数)。工厂函数可以是您展示的静态方法、其他类型对象的方法或只是常规函数(基本上是任何类型的函数,静态或非静态)。
因此,假设您的代码中有四个地方都创建了相同类型的对象,并且构造函数的参数相同或几乎相同。无需将该代码复制到四个位置,您只需创建一个共享函数来为您完成所有常见工作,然后您可以在多个位置使用它,就像将任何其他通用代码放入共享函数中一样。除非您正在创建和返回一个对象,否则该类型的共享函数有一个特定的名称(工厂函数)。正如我之前所说,工厂函数可以是任何类型的函数(只要最适合您的编码设计),因此静态方法当然是可接受的编码方式之一。
With ES6 Classes, is it ok to return an instantiation of that class from a static method?
是的,在函数式编程中也很常见
class Box {
constructor (value) {
this.value = value
}
fmap (f) {
return Box.of (f (this.value))
}
concat ({value}) {
return Box.of (this.value + value)
}
static of (value) {
return new Box (value)
}
}
const sq = x => x * x
let b = Box.of(3).fmap(sq).concat(Box.of(4).fmap(sq))
console.log (b)
// { Box 3*3 + 4*4 }
// { Box 25 }
class Thing {
constructor(parameter) {
if (parameter) {
this.x = parameter;
}
return this;
}
getX () {
return this.x;
}
static specialThing() {
return new Thing('Special Thing');
}
}
let thingy = Thing.specialThing();
thingy.getX(); // 'Special Thing'
我想在 JavaScript 中执行上述操作(尽管形式更复杂)。当我 运行 这段代码时,它 运行 目前很好,但是我觉得在 class return 中有一个函数 class 的实例化版本感到奇怪。有什么理由不以这种方式构建我的代码吗?
静态方法的替代方法是:
Thing.specialThing = () => {
return new Thing('Special Thing');
};
使用这些东西中的任何一个都有哪些优点和缺点(如果有的话)?还有其他我不知道的更好的方法来实现这个目标吗?
With ES6 Classes, is it ok to return an instantiation of that class from a static method?
当然,这很好,在某些情况下这是一种公认的做法。当您想将可重用函数编码为可从多个位置调用的可重用函数时,通常会使用它,这是一种调用构造函数和创建对象的特定方式。
名为 specialThing
的静态函数称为工厂函数(一个为您创建并 returns 对象的常规函数)。工厂函数可以是您展示的静态方法、其他类型对象的方法或只是常规函数(基本上是任何类型的函数,静态或非静态)。
因此,假设您的代码中有四个地方都创建了相同类型的对象,并且构造函数的参数相同或几乎相同。无需将该代码复制到四个位置,您只需创建一个共享函数来为您完成所有常见工作,然后您可以在多个位置使用它,就像将任何其他通用代码放入共享函数中一样。除非您正在创建和返回一个对象,否则该类型的共享函数有一个特定的名称(工厂函数)。正如我之前所说,工厂函数可以是任何类型的函数(只要最适合您的编码设计),因此静态方法当然是可接受的编码方式之一。
With ES6 Classes, is it ok to return an instantiation of that class from a static method?
是的,在函数式编程中也很常见
class Box {
constructor (value) {
this.value = value
}
fmap (f) {
return Box.of (f (this.value))
}
concat ({value}) {
return Box.of (this.value + value)
}
static of (value) {
return new Box (value)
}
}
const sq = x => x * x
let b = Box.of(3).fmap(sq).concat(Box.of(4).fmap(sq))
console.log (b)
// { Box 3*3 + 4*4 }
// { Box 25 }