从构造函数调用方法:错误:未捕获TypeError:undefined不是函数 [英] Call Method from Constructor: Error: Uncaught TypeError: undefined is not a function
问题描述
任务:我需要在Typescript中构建一个类,它在自己的构造函数中调用它自己的一些方法。
Task: I need to build a class in Typescript that calls some of it's own methods in it's own Constructor.
问题:以下示例代码所代表的实际代码将成功编译,但在Javascript控制台中进行测试后,它不会。
Problem: The Actual Code that the following Sample Code represents will Compile Successfully, but upon testing in the Javascript Console, it does not.
示例:
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
}
}
技术: Typescript编译器没有问题 this.setupAudioNodes()
但是在浏览器的Javascript控制台中一旦被称为Javascript我收到错误未捕获的TypeError:undefined不是函数
。实际上,这是Javascript的这个。
语法以及如何容易与之混淆的问题。但是因为我在使用Typescript开发,我想要一个更多的Typescript风格的解决方案。
Technical: The Typescript Compiler does not have a problem with this.setupAudioNodes()
but once called as Javascript within the Browser's Javascript Console I receive an error Uncaught TypeError: undefined is not a function
. Effectively, this is an issue with Javascript's this.
syntax and how it's easy to get confused with it. But because I'm developing in Typescript, I want a more Typescript style solution.
问题:如何从它调用类的方法打字稿中的构造函数?
Question: How can I call a Class's Methods from it's Constructor in Typescript?
推荐答案
以下是如何从构造函数中调用方法:
Here's how to call a method from the constructor:
class Thing {
constructor(name: string) {
this.greet(name);
}
greet(whatToGreet: string) {
console.log('Hello, ' + whatToGreet + '!')
}
}
var x = new Thing('world'); // Prints "Hello, world!"
这篇关于从构造函数调用方法:错误:未捕获TypeError:undefined不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!