Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们可以访问typescript中另一个类中的私有变量吗_Typescript - Fatal编程技术网

我们可以访问typescript中另一个类中的私有变量吗

我们可以访问typescript中另一个类中的私有变量吗,typescript,Typescript,嗨,我是这个类型脚本的新手,在animal类中,我创建了一个私有变量名,我在类构造函数中使用了它。现在在类Tiger中,我为Animal类创建了一个实例,并能够访问该私有变量 我的问题是在Java中,如果我们这样做,我们将得到错误。但是在TypeScript中(因为TypeScript支持OOPS),我们没有得到任何错误,而且它给出了值“如何可能”?首先-您的代码将无法编译。TypeScript将检查名称的可访问性,并给出一个错误。在typescript游乐场检查自己: 第二,如果删除类型脚本检

嗨,我是这个类型脚本的新手,在animal类中,我创建了一个私有变量名,我在类构造函数中使用了它。现在在类
Tiger
中,我为
Animal
类创建了一个实例,并能够访问该私有变量


我的问题是在Java中,如果我们这样做,我们将得到错误。但是在TypeScript中(因为TypeScript支持OOPS),我们没有得到任何错误,而且它给出了值“如何可能”?

首先-您的代码将无法编译。TypeScript将检查名称的可访问性,并给出一个错误。在typescript游乐场检查自己:

第二,如果删除类型脚本检查,则可以访问私有属性,例如:

class Animal {
    private name:string;
    public Firstname:string;
    constructor(theName: string)
    {
        this.name = theName;
        this.Firstname=theName;
    }
}

class Tiger {
    function sample(){
        Animal animalName=new Animal('Tiger');
        document.body.innerHTML = animalName.name;
    }
    sample();
}
console.log((animalName.name)

这是因为本机JavaScript没有私有属性的概念。当TypeScript被编译成JavaScript时,您就有了这种可能性。

使用
作为任何
技巧的替代方法是使用字符串索引符号,这是访问私有成员的一种方法:

console.log(animalName['name']);

这具有类型安全的优点,因此如果您删除
名称
,您将在此处遇到编译器错误。

直接从另一个类访问私有变量是不可能的,但可以通过getter和setter方法来实现。

+1回答得好。我想提到的是,依赖于
private
在运行时不是私有的这一事实,会使代码迁移在某一点上变得更加困难,并大大降低可维护性。OP应该重新考虑他们的设计。如果你使用的是eslint的
点表示法
规则,你可能会得到警告。考虑采用一个约定,让所有的私人成员从下划线开始;这样,您就可以更新您的eslint配置,使其具有
'dot-notation':['error',{allowPattern:'^.}],
以忽略这些字段。@JamesWilkins,这是关于
只读
私有的
。对了,谢谢您捕捉到@timmm.)
console.log((<any>animalName).name)