Typescript类方法返回undefined



我创建了一个typescript类,里面有两个函数,用来计算喜欢和不喜欢的比例。

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);
}

,但当我创建一个MyClass实例,如myClass:MyClass = {thumbedUp: 10, thumbedDown: 12};和我尝试调用MyClass。像%,它返回未定义。我真的不明白为什么我的对象被实例化了…你能帮我吗?

感谢
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);
}


}


相关内容

  • 没有找到相关文章

最新更新