我是新手typescript
,并且尝试将 javascript 代码转换成 typescript,所以我最终得到了下面的代码。我对typescript中的类的理解如下,可能有误,是: 1.定义类后,必须用 来声明后面要使用的参数this
,减速的形式为variableName:variableType
。2. 在构造函数中,变量可以赋值为this.variableName = x
3. 在methods
下面的class
变量中可以使用 withthis.
在下面的代码中,我收到了错误[ts] Property 'escapeRegExp' does not exist on type 'typeof Listen'.
,如附图所示。
namespace CORE{
export class Listen{
commandsList:[RegExp, string, string];
debugStyle:string;
optionalParam:RegExp;
optionalRegex:RegExp;
namedParam:RegExp;
splatParam:RegExp;
escapeRegExp:RegExp;
constructor(){
this.commandsList = [];
this.debugStyle = 'font-weight: bold; color: #00f;';
this.optionalParam = /\s*\((.*?)\)\s*/g;
this.optionalRegex = /(\(\?:[^)]+\))\?/g;
this.namedParam = /(\(\?)?:\w+/g;
this.splatParam = /\*\w+/g;
this.escapeRegExp = /[\-{}\[\]+?.,\\\^$|#]/g;
}
public static commandToRegExp(command:string):RegExp{
command = command.replace(this.escapeRegExp, '\\$&')
.replace(this.optionalParam, '(?:$1)?')
.replace(this.namedParam, function(match, optional) {
return optional ? match : '([^\\s]+)';
})
.replace(this.splatParam, '(.*?)')
.replace(this.optionalRegex, '\\s*$1?\\s*');
return new RegExp('^' + command + '$', 'i');
}
public static registerCommand(command:RegExp, cb:string, phrase:string):void{
this.commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
}
public static addCommands(commands:string[]):void{
var cb;
for (var phrase in commands) {
if (commands.hasOwnProperty(phrase)) {
cb = this[commands[phrase]] || commands[phrase];
if (typeof cb === 'function') {
// convert command to regex then register the command
this.registerCommand(this.commandToRegExp(phrase), cb, phrase);
} else if (typeof cb === 'object' && cb.regexp instanceof RegExp) {
// register the command
this.registerCommand(new RegExp(cb.regexp.source, 'i'), cb.callback, phrase);
}
}
}
}
public static executeCommand(commandText:string):void{
for (var j = 0, l = this.commandsList.length; j < l; j++) {
var result = this.commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
// execute the matched command
this.commandsList[j].callback.apply(this, parameters);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
this
不存在于静态方法中。静态方法不依赖于类实例。关于静态方法的阅读有很多,但基本上:类方法可以调用静态方法,静态方法不能调用类方法(没有实例)。
这里的解决方法是从您的方法中删除static
。
归档时间: |
|
查看次数: |
23650 次 |
最近记录: |