JTh*_*ora 8 javascript syntax html5 grammar typescript
任务:我需要在Typescript中构建一个类,它在它自己的构造函数中调用它自己的一些方法.
问题:以下示例代码表示的实际代码将成功编译,但在Javascript控制台中进行测试时,它不会.
样品:
export class volumeEQ
{
constructor(ctx:any)
{
this.ctx = ctx; // Audio context saved into member variable of class
this.setupAudioNodes(); // Sets up nodes made out of audio
}
setupAudioNodes()
{
this.sourceNode.connect(this.ctx.destination); // Connect to destination
}
}
Run Code Online (Sandbox Code Playgroud)
技术: Typescript编译器没有问题this.setupAudioNodes()但在浏览器的Javascript控制台中一旦被称为Javascript我收到错误Uncaught TypeError: undefined is not a function.实际上,这是Javascript this.语法的一个问题,以及如何容易与它混淆.但是因为我在使用Typescript开发,我想要一个更多的Typescript风格的解决方案.
问题:如何从Typescript中的构造函数调用类的方法?
Rya*_*ugh 10
以下是如何从构造函数调用方法:
class Thing {
constructor(name: string) {
this.greet(name);
}
greet(whatToGreet: string) {
console.log('Hello, ' + whatToGreet + '!')
}
}
var x = new Thing('world'); // Prints "Hello, world!"
Run Code Online (Sandbox Code Playgroud)
以下是我要找的.
解决方案来源:
如何使用回调函数在TypeScript中保留词法范围
this.打字稿中的词法范围:如果方法的以下声明不起作用:
export class myClass
{
constructor()
{
var myString:string = this.myMethod(true);
}
public myMethod(useBigString:boolean) : string
{
if(useBigString)
{
return "bigString";
}
return "smlStr";
}
}
Run Code Online (Sandbox Code Playgroud)
它在javascript中生成一个方法,如下所示:
myClass.prototype.myMethod = function (useBigString) {
Run Code Online (Sandbox Code Playgroud)
相反,尝试以这种方式声明您的方法:
export class myClass
{
constructor()
{
var initString:string = this.myMethod(true);
}
public myMethod = (useBigString:boolean) : string => {
if(useBigString)
{
return "bigString";
}
return "smlStr";
}
}
Run Code Online (Sandbox Code Playgroud)
它在构造函数中声明javascript中的方法:
this.myMethod = function(useBigString) {
Run Code Online (Sandbox Code Playgroud)
缺点是方法语法突出显示不会识别这种定义,但它绝对是编译和工作!这种情况不适用于类变量,就像类方法一样.
| 归档时间: |
|
| 查看次数: |
11157 次 |
| 最近记录: |