0

Can somebody give me answer to the following two questions:

1) Why isn't it possible to declare variables in methods like an attribute in the comprehensive class?

What I want: private foo: string (compiler error)
What I have to do: var foo: string (no compiler error)

2) When do I declare a variable as an attribute of the class and when do I declare a variable only in the method? I'm not sure if the Java knowledge fits in this case. Spontaniously I would say it depends on the scope of the variable (if it is needed f.e. in two or more methods -> attribute of class OR otherwise -> variable of a method).

Thank you!

1
  • 2
    Because variable created inside method have only one possible scope - method scope. Commented Nov 7, 2015 at 23:24

1 Answer 1

2

Answering you would be easier if you mentioned what you're trying to do.

TypeScript private class members aren't actually private at runtime; if you want actual privacy, you should use a closure like so:

class Foo {
  getSomethingPrivate: () => number
  constructor() {
    var somethingPrivate = 1;
    this.getSomethingPrivate = function() {
      return somethingPrivate;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.