如何正确处理打字稿中的范围

编程入门 行业动态 更新时间:2024-10-19 00:20:01
本文介绍了如何正确处理打字稿中的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对上下文有疑问.处理打字稿中上下文的正确方法是什么?如果我正确理解它,我对闭包有疑问吗?当我在对象(类)中的函数内部调用函数时,那是闭包吗?

I have a question about context. What is to proper way to deal with context in typescript? If I understand it correctly I have a problem with closures? When I'm calling a function inside a function, which is in object (class) then it's a closure right?

但是我必须使用 self = this 还是在打字稿中有更好的方法?因为我真的不喜欢这种解决方案.而且我不想束缚每一件事.

But do I have to use self = this or is there a better way in typescript please? Because I really don't like this solution. And I don't want to bind every little thing.

关于托尔金的例子:

export class SomeClass { private declaration; constructor() {} ngOnInit(){ var self = this; some code var interval = setInterval(function() { self.someFunction(); }, 1000); } someFunction() { something } }

谢谢您的建议

推荐答案

在这种情况下,您可以使用箭头函数语法,它将捕获 this 的值以按您期望的那样引用类原型:

In this case, you can use the arrow function syntax, which will capture the value of this to refer to the class prototype as you would expect:

ngOnInit() { some code var interval = setInterval(() => { this.someFunction(); }, 1000); }

更多推荐

如何正确处理打字稿中的范围

本文发布于:2023-11-24 04:38:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确处理

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!