使用函数类方法而不是实际的类对象,我如何在类对象内完成声明静态方法并通过该名称访问它。
最终目标是同时声明这两件事。
请忽略非标准符号和隐式变量。代码确实像在浏览器控制台内一样运行,因此即使不是标准代码,也是有效的。看它更像是伪代码。
第 1 部分:使此模式成立
Be able to use a declared variable name ('Array') as a constructor ('new Array()')
Be able to use static methods available to same declared variable name ('Array') accessed as an object ('Array.isArray()').
第 2 部分:执行此操作
标题:显而易见的解决方案
declare some class name function ('foo')
As part of created js-object when declaring functions, declare property-method accessing same declared class function name ('foo.isFoo')
declare instance of class ('foo')
第三节 像这样
标题:目标和理想
declare some class name function ('foo') with intended static method ('isFoo') to be accessed from main class name ('foo.isFoo')
declare instance of class ('foo')
try: what throws an error because ('foo.isFoo') isn't a function but ('c.isFoo') is. How do we declare this as a static function?
catch: just garbage to throw at the end console feed for clarity
指示
a = "animal";
/* So that this pattern holds */
console.log("nSo that this pattern holds")
b = new Array(a);
console.log("new Array(a) = [" + b + "]");
console.log("Array.isArray(b) = " + Array.isArray(b));
/* DO THIS */
console.log("nDO THIS");
foo = function (f) {
this.f = f;
}
foo.isFoo = c => c instanceof foo;
c = new foo(a);
console.log("new foo(a) = " + c);
console.log("foo.isFoo(c) = " + foo.isFoo(c));
/* LIKE THIS */
console.log("nLIKE THIS");
foo = function (f) {
this.f = f;
this.isFoo = c => c instanceof foo;
}
c = new foo(a);
console.log("new foo(a) = " + c);
try {console.log("foo.isFoo(c) = " + foo.isFoo(c));}
catch {console.log("foo.isFoo is not a functionn foo.isFoo(c) should = true");}
控制台输出
So that this pattern holds debugger eval code:4:9
new Array(a) = [animal] debugger eval code:6:9
Array.isArray(b) = true debugger eval code:7:9
DO THIS debugger eval code:10:9
new foo(a) = [object Object] debugger eval code:16:9
foo.isFoo(c) = true debugger eval code:17:9
LIKE THIS debugger eval code:20:9
new foo(a) = [object Object] debugger eval code:26:9
foo.isFoo is not a function
foo.isFoo(c) should = true
这意味着在行为上与此相同
class Point {
constructor( ...args ) {
...do stuff...
}
static isPoint( c ) { return c instanceof this; }
}
point = new Point( 3, 7 );
console.log( Point.isPoint( point ) );
console.log( Point.isPoint( Object ) );
好的,编辑后我理解你的问题。
TL;DR不,没有好方法可以做你想做的事。
在构造函数中this
被new
运算符绑定为新创建的实例,没有像类静态方法那样动态引用类本身的方法:
function Foo1 () {
this; // <- instance
}
class Foo2 {
static bar () {
this; // <- class Foo2
}
constructor () {
this; // <- instance
}
}
我认为根据您在问题中发布的内容,到目前为止,您了解了所有这些内容,并希望在第二个示例中复制简洁的静态函数声明。
您可以这样做:
function Foo3 () {
Foo3.bar = function() {
this; // <- class Foo3
}
}
这似乎可以做你想做的,除了每次调用new Foo3
时都会重新定义bar
静态方法。另外,您仍然必须按名称引用该类,您不能像在类静态方法中使用this
那样动态访问它。