简体   繁体   English

Angular 2组件变量范围和参考

[英]Angular 2 component variable scope and references

Is there a way to avoid always having to attach a "this" to referencing private Component variables or functions? 有没有一种方法可以避免始终必须在引用私有Component变量或函数时附加“ this”?

For example, the following will cause a "Cannot find name" error on "foo" 例如,以下内容将导致“ foo”上出现“找不到名称”错误

export class SomeComponent {
    private foo = 5;

    someMethod(){
        console.log(foo);
    }
}

To fix, I need to attach a "this" to the foo variable, as in: 要修复,我需要在foo变量上附加一个“ this”,如下所示:

console.log(this.foo);

I'm all for strong identification of variables, but this seems overly strict given the smaller size of most Angular components. 我全力支持变量的识别,但是鉴于大多数Angular组件的尺寸较小,这似乎过于严格。

In JavaScript and TypeScript you need to refer to the fields and functions of the class in that class with the this keyword JavaScriptTypeScript您需要使用this关键字引用该类中该类的字段和函数。

From The Documentation of TypeScript TypeScript文档中

Let's take a look at a simple class-based example: 让我们看一个基于类的简单示例:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

The syntax should look familiar if you've used C# or Java before. 如果您以前使用过C#或Java,则语法看起来应该很熟悉。 We declare a new class Greeter. 我们宣布一个新类别的问候者。 This class has three members: a property called greeting, a constructor, and a method greet. 此类具有三个成员:称为Greeting的属性,构造函数和greet方法。

You'll notice that in the class when we refer to one of the members of the class we prepend this.. This denotes that it's a member access. 您会注意到,在类中,当我们引用该类的成员之一时,会在此前缀前面。这表示它是成员访问权限。

不,这是标准的OO编程,我不知道不使用该语言就不会引用类成员变量的语言

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

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