gpt4 book ai didi

javascript - 在 Typescript 中访问对象类的静态方法?

转载 作者:行者123 更新时间:2023-11-30 19:09:52 24 4
gpt4 key购买 nike

class Base {
static f(){console.log('Base')}
}

class A extends Base {
static f(){console.log('A')}
}

class B extends Base {
static f(){console.log('B')}
}

let obj: A|B = new A()

obj.<what to put here>.f()

我不知道 obj 的确切类,我需要打印 A 或调用 f() 以获得正确的 obj 类。

我不需要的只是类名,例如。我正在做更复杂的事情。

prototype, typeof, constructor 好像都是语法错误。

最佳答案

两者都是Object.getPrototypeOf() (替换现已弃用的 Object.prototype.__proto__ )或 Object.prototype.constructor应该工作:

Object.getPrototypeOf(obj).constructor.f();

obj.constructor.f();

实际上:

Object.getPrototypeOf(obj).constructor === obj.constructor; // true

在这里你可以看到运行中的编译源代码:

class Base {
static f() { console.log('Base'); }
}

class A extends Base {
static f() { console.log('A'); }
}

class B extends Base {
static f() { console.log('B'); }
}

const objBase = new Base();
const objA = new A();
const objB = new B();

Object.getPrototypeOf(objBase).constructor.f();
objBase.constructor.f();

Object.getPrototypeOf(objA).constructor.f();
objA.constructor.f();

Object.getPrototypeOf(objB).constructor.f();
objB.constructor.f();

console.log(Object.getPrototypeOf(objB).constructor === objB.constructor);
console.log(Object.getPrototypeOf(objB) === B.prototype);
.as-console-wrapper {
max-height: none !important;
}

注意静态属性存在于类中但不存在于实例中。

因此,如果你想从obj到它的原型(prototype),你应该调用Object.getPrototypeOf(obj),而不是obj.prototype,这是完全不同的事情。

.prototype 属性仅存在于函数中,并且在使用 new 实例化新对象并调用该构造函数时 (new A()), 将成为新创建对象的原型(prototype)(已弃用的 .__proto__)。

在你的例子中:

obj.prototype;                // undefined
A; // class A { static f() { ... } }
A.protoype; // { constructor: class A { ... } }
A.protoype.constructor; // class A { static f() { ... } }
A.protoype.constructor === A; // true
obj.constructor; // class A { static f() { ... } }
obj.constructor === A; // true

Object.getPrototypeOf(obj) === A.prototype; // true

关于javascript - 在 Typescript 中访问对象类的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com