So in C# when I've been creating model classes and lazy loading things, I do something like this:
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? 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:
There is no equivalent.
Every member access in JavaScript is subject to dynamic dispatch by definition. This is because member access in JavaScript is morally a key lookup in a hash table.
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):
class baseClass {
doSomething = () => {};
}
class derivedClass extends baseClass {
constructor() {
this.doSomeThing = () => { console.log('something'); };
}
}
Javascript 和 Typescript 中的所有方法在技术上都是虚拟的,因为没有什么可以阻止您覆盖任何方法。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.