简体   繁体   English

TypeScript:在构造函数中使用private或public

[英]TypeScript: use private or public in constructor

I'm new to TypeScript world, and I've seen examples with this to deal with injected objects and set it to a property of the component (this.anything) 我是TypeScript世界的新手,我已经看过这个例子来处理注入的对象并将其设置为组件的属性(this.anything)

First with public and setting by hand to this.nav 首先是公开并手动设置this.nav

export class XPTO {
   constructor(public nav: NavController) {
      this.nav = nav;
   }
}

and this, with private 而这,私人

export class XPTO {
   constructor(private nav: NavController) {
      //this.nav is nav?
   }
}

in both cases after construct the object this.nav is a NavController object. 在构造对象之后的两种情况中,this.nav都是一个NavController对象。 What are the differences of both implementations? 两种实现有何不同? Or this is the same when compiled to plain javascript? 或者在编译为普通javascript时这是一样的吗?

Actually in your first example the explicit assignment is not needed at all: 实际上,在您的第一个示例中,根本不需要显式赋值:

export class XPTO {
   constructor(public nav: NavController) {
       // This line is not required.
       // this.nav = nav;
       this.someFunction();
   }
   someFunction(){
       console.log(this.nav); // Prints out the NavController.
   }
}

Whenever you specify public or private on a constructor parameter a corresponding public/private variable is created on the class and filled with the value of the parameter. 无论何时在构造函数参数上指定public或private,都会在类上创建相应的公共/私有变量,并使用参数的值填充该变量。

So really, the only difference of the two code samples is that one is private and the other one is public. 实际上,两个代码示例的唯一区别是一个是私有的,另一个是公共的。

The resulting JavaScript will be the same. 生成的JavaScript将是相同的。 However, the compiler will throw an error, if you are trying to access private variables in your code. 但是,如果您尝试访问代码中的私有变量,编译器将抛出错误。

public and private , as a lot of Typescript features, are only TypeScript modifiers. publicprivate ,作为很多Typescript特性,只是TypeScript修饰符。 I'm not sure the compiler names these variables exactly the same, but from a JavaScript point of view, the code will be essentially the same. 我不确定编译器是否将这些变量命名为完全相同,但从JavaScript的角度来看,代码基本相同。

The interest of Typescript is to give you features like type checking, it doesn't necessarily always modifies the outputted code. Typescript的兴趣在于为您提供类型检查等功能,它不一定总是修改输出的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM