刚开始使用TypeScript,我找不到这个问题的解释......
让我说我有功能
function test() {
function localAccessMethod() {
console.log('I am only accessable from inside the function :)');
}
this.exposedMethod = function () {
console.log('I can access local method :P');
localAccessMethod();
}
}
我想把它转换成打字稿类...到目前为止,我已经做到了这里:
class test {
constructor: {}
exposedMethod() {
console.log('I can access local method :P');
localAccessMethod();
}
}
如何在typescript类中定义本地函数,因此它不会作为原型或.this公开?
或者更好的问题,我应该如何转换源代码以适应TypeScript标准。我想要的功能只适用于所有类方法,但不会暴露...
答案 0 :(得分:1)
您可以使用private static
个关键字:
class Test
{
private static localAccessMethod()
{
console.log('I am only accessable from inside the function :)');
}
exposedMethod()
{
console.log('I can access local method :P');
Test.localAccessMethod();
}
}
答案 1 :(得分:0)
你不能在一个不会暴露的类中拥有某些内容,甚至私有/受保护的成员/方法也会在javascript中公开,只有编译器强制实现这种可见性。
您有几个选择:
(1)在主要内部有“内部”功能:
export class test {
constructor() {}
exposedMethod() {
console.log('I can access local method :P');
function localAccessMethod() {
console.log('I am only accessable from inside the function :)');
}
localAccessMethod();
}
}
(2)如果这是一个模块,那么将内部函数放在模块的顶层部分,不要导出它:
function localAccessMethod() {
console.log('I am only accessable from inside the function :)');
}
export class test {
constructor() {}
exposedMethod() {
console.log('I can access local method :P');
localAccessMethod();
}
}
(3)如果你没有使用模块,那么将这个东西包装在命名空间中并只输出类:
namespace wrapping {
function localAccessMethod() {
console.log('I am only accessable from inside the function :)');
}
export class test {
constructor() {}
exposedMethod() {
console.log('I can access local method :P');
localAccessMethod();
}
}
}