[英]Equivalent of c# class virtual member in TypeScript
So in C# when I've been creating model classes and lazy loading things, I do something like this:因此,在 C# 中,当我创建模型类和延迟加载时,我会执行以下操作:
public int? User_ID { get; set; }
public int? Dept_ID { get; set; }
Then a little farther down in my class I pop in my virtuals like so:然后在我的班级再往下一点,我像这样弹出我的虚拟机:
public virtual User User {get; set;}
public virtual Department Dept {get; set;}
How would I do this in Typescript?我将如何在 Typescript 中执行此操作? Something like this?:
像这样的东西?:
User_ID: number;
Dept_ID: number;
User: User;
Dept: Department;
I don't think interfaces is what I want/need...but then again protected doesn't seem correct either.我不认为接口是我想要/需要的......但是再次受保护似乎也不正确。 Something tells me I'm missing an obvious answer here.
有些东西告诉我我在这里错过了一个明显的答案。
The following applies equally to TypeScript and JavaScript:以下同样适用于 TypeScript 和 JavaScript:
There is no equivalent.没有等价物。
Every member access in JavaScript is subject to dynamic dispatch by definition. JavaScript 中的每个成员访问都根据定义进行动态调度。 This is because member access in JavaScript is morally a key lookup in a hash table.
这是因为 JavaScript 中的成员访问在道德上是在哈希表中的键查找。
An object may declare a member with the same key as one it inherits via the prototype chain and thereby shadow the inherited member but this is not the same as virtualness, a concept not present in the language.一个对象可以声明一个成员与它通过原型链继承的成员具有相同的键,从而隐藏被继承的成员,但这与虚拟性不同,虚拟性是语言中不存在的概念。
Yes there are ..是的,有..
//non-abstract or abstract class
class A {
// The virtual method
protected virtualStuff1?():void;
public Stuff2(){
//Calling overridden child method by parent if implemented
this.virtualStuff1 && this.virtualStuff1();
alert("Baseclass Stuff2");
}
}
//class B implementing virtual method
class B extends A{
// overriding virtual method
public virtualStuff1()
{
alert("Class B virtualStuff1");
}
}
//Class C not implementing virtual method
class C extends A{
}
var b1 = new B();
var c1= new C();
b1.Stuff2();
b1.virtualStuff1();
c1.Stuff2();
I achieved this using an arrow function as a property of the class (note this was in ts, but if you're handy at modern js it should work):我使用箭头函数作为类的属性实现了这一点(注意这是在 ts 中,但如果你在现代 js 中很方便,它应该可以工作):
class baseClass {
doSomething = () => {};
}
class derivedClass extends baseClass {
constructor() {
this.doSomeThing = () => { console.log('something'); };
}
}
Javascript 和 Typescript 中的所有方法在技术上都是虚拟的,因为没有什么可以阻止您覆盖任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.