Node.js 宣布';这';辅助函数的值
我有一门课:Node.js 宣布';这';辅助函数的值,node.js,typescript,typescript2.0,tsc,Node.js,Typescript,Typescript2.0,Tsc,我有一门课: const helper = function(val){ console.log(this.a); console.log(this.b); this.bar(); }; export class Foo { public b = '45' private a = 15; bar(){ } myMethod(){ return helper.apply(this,arguments); } } 问题是,在helper函数中,它不
const helper = function(val){
console.log(this.a);
console.log(this.b);
this.bar();
};
export class Foo {
public b = '45'
private a = 15;
bar(){
}
myMethod(){
return helper.apply(this,arguments);
}
}
问题是,在helper函数中,它不知道上下文是什么(this的值是什么)
有没有办法告诉typescript,helper函数中的这个值是Foo
的一个实例
(我使用helper函数的原因是创建真正的私有方法)。尝试在helper函数上添加以下内容:
let self: Foo = this as Foo;
// use self instead of this below
或者,您可以将其中的
this
的所有实例替换为(此为Foo)
尝试将其添加到助手函数的顶部:
let self: Foo = this as Foo;
// use self instead of this below
或者,您可以将其中的
this
的所有实例替换为(此为Foo)
您可以通过添加名为this
的额外参数来声明任何函数的this
的类型。此
参数将不会发送到Javascript,这只是为了让编译器能够检查代码的类型:
const helper = function(this: Foo, val: number){
console.log(this.a); /// error a is private
console.log(this.b);
this.bar();
};
但是,这不会破坏封装,您仍然无法从类外部访问私有属性,因此,除非您在类内部创建函数,否则它仍然会给出如上所述的错误。对于类内定义的函数,它不会给出错误:
export class Foo {
public b = '45'
private a = 15;
bar() { }
createHelper() {
return function (this: Foo, val: number) {
console.log(this.a);
console.log(this.b);
this.bar();
};
}
myMethod() {
return this.createHelper().apply(this, arguments);
}
}
通过添加名为this
的额外参数,可以为任何函数
声明this
的类型。此
参数将不会发送到Javascript,这只是为了让编译器能够检查代码的类型:
const helper = function(this: Foo, val: number){
console.log(this.a); /// error a is private
console.log(this.b);
this.bar();
};
但是,这不会破坏封装,您仍然无法从类外部访问私有属性,因此,除非您在类内部创建函数,否则它仍然会给出如上所述的错误。对于类内定义的函数,它不会给出错误:
export class Foo {
public b = '45'
private a = 15;
bar() { }
createHelper() {
return function (this: Foo, val: number) {
console.log(this.a);
console.log(this.b);
this.bar();
};
}
myMethod() {
return this.createHelper().apply(this, arguments);
}
}
这里有一个StackBlitz:(这是一个有角度的文件,但我只是使用main.ts作为一个typescript文件)。检查浏览器控制台,它的行为似乎与您所希望的一样。这在运行时正常工作。。。但是在编译时,TS不知道这是什么(它不知道,因为它是动态的,除非你告诉TS它总是一种类型),那么让self:Foo=this作为Foo编码>然后使用self
?也可以在每次使用时将这个替换为(这是Foo)
。@zerkms我实际上试过了,它说t
的私有方法/成员不能被t
访问,即使它被声明为Foo
,跛脚!哦,对了。我明白了,你想要一个在JS运行时不可用的私有方法。检查浏览器控制台,它的行为似乎与您所希望的一样。这在运行时正常工作。。。但是在编译时,TS不知道这是什么(它不知道,因为它是动态的,除非你告诉TS它总是一种类型),那么让self:Foo=this作为Foo编码>然后使用self
?也可以在每次使用时将这个替换为(这是Foo)
。@zerkms我实际上试过了,它说t
的私有方法/成员不能被t
访问,即使它被声明为Foo
,跛脚!哦,对了。所以你想要一个在JS运行时不可用的私有方法,我明白了。@AlexanderMills我不发布未测试的代码,它是编译的;)@AlexanderMills我不会发布未经测试的代码,它会编译;)