[英]Typescript class method returns undefined
I have created a typescript class, and i have two functions inside it, which are supposed to compute the ratio of likes and dislikes.我创建了一个 typescript class,里面有两个函数,它们应该计算喜欢和不喜欢的比例。
export class MyClass {
thumbedUp?: number;
thumbedDown?: number;
likePercent?= () => Math.round((this.thumbedUp / (this.thumbedDown + this.thumbedUp)) * 100);
dislikePercent?= () => Math.round((this.thumbedDown / (this.thumbedDown + this.thumbedUp)) * 100);
}
but when i create a MyClass instance like myClass:MyClass = {thumbedUp: 10, thumbedDown: 12};
但是当我创建一个 MyClass 实例时,比如
myClass:MyClass = {thumbedUp: 10, thumbedDown: 12};
and i try to call myClass.likePercent, it returns undefined.我尝试调用 myClass.likePercent,它返回未定义。 I really don't understand why as my object is instanciated... Can you help me?
我真的不明白为什么我的 object 被实例化了......你能帮我吗?
Thanks谢谢
export class MyClass {
thumbedUp: number;
thumbedDown: number;
constructor(thumbedUp:number, thumbedDown:number ){
this.thumbedDown=thumbedUp;
this.thumbedUp=thumbedDown;
}
likePercent():number{
return Math.round((this.thumbedUp / (this.thumbedDown + this.thumbedUp)) * 100);;
}
dislikePercent():number{
return Math.round((this.thumbedDown / (this.thumbedDown + this.thumbedUp)) * 100);
}
}
var myclass = new MyClass(10,12);
console.log(myclass.likePercent())
do like me喜欢我
export class MyClass {
thumbedUp: number;
thumbedDown: number;
constructor(){
this.thumbedDown=0;
this.thumbedUp=0;
}
likePercent():number{
return Math.round((this.thumbedUp / (this.thumbedDown + this.thumbedUp)) * 100);;
}
dislikePercent():number{
return Math.round((this.thumbedDown / (this.thumbedDown + this.thumbedUp)) * 100);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.