Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does variable declaration differ between the `class` and `constructor`?

I have seen an example, and I am trying to reproduce it. The name and age are declared inside the class and services ( Injectable ) added in the constructor.

I'd like to know the difference between declaring variable with class and constructor here. Any one help me to know the differences.

As well instead of declaring the name and age can't I declare inside of the constructor itself?

here is my code :

    import {Component} from 'angular2/core';
    import {CommonService} from './commonService';
    import {commonServiceIndipendent} from './commonSerivceIndipendent';

    @Component({

      selector : 'component1',

      template : `

        <h1>Component 1</h1>
        <input type="text" #message />

        <button (click)="onLog(message.value)" >Component1 - Message </button>

      `,

      providers:[commonServiceIndipendent]

    })

    export class Component1 {

      name:string; //why here?
      age:number; //why here?

//can't i add to constructor? if so how?
      constructor ( 
        private _commonService : CommonService, 
        private _commonServiceIndipendent:commonServiceIndipendent) {}


      //sending to same service. it has other instance in history
      onLog(message:string) {

        this._commonService.log( message );

        this.name = "Arif",
        this.age = 20;

        this.onData();

      }

      onData() {
        this._commonServiceIndipendent.myData(this.name,this.age);
      }

    }
like image 855
user2024080 Avatar asked Mar 22 '16 06:03

user2024080


People also ask

How do you declare a variable in a constructor?

Objects are created in programs by declaring a variable of the class and using the keyword new followed by a call to a constructor. Constructors set the initial values for the object's instance variables.

What is the difference between declaring and instantiating a variable in Java?

When you declare a variable, you give it a name (name/age) and a type (String/int): String name; int age; Initializing a variable is when you give it a value.

What is variable and variable declaration?

Difference b/w variable declaration and definition: Variable declaration refers to the part where a variable is first declared or introduced before its first use. Declaration of variable type is also done in the part. A variable definition is a part where the variable is assigned a memory location and a value.

How do you declare a variable in Java?

Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

When is the constructor of a class called?

The constructor () method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method. Note: A class cannot have more than one constructor () method.

How to force a constructor to use a class variable?

When that happens, the compiler will favor the constructor parameter (or method parameter, or local variable) over the class variable. In order to "force" it to use the class variable, you prefix it with this.. The thing to keep in mind is that the two variables are totally separate, regardless of their names.

What is the use of a constructor in Java?

The constructor is used to create any object, it doesn’t belong to any class, but you can lock the properties for a certain class if you want to. The class just uses the constructor to create objects.

Can a class have more than one constructor () method?

Note: A class cannot have more than one constructor () method. This will throw a SyntaxError. You can use the super () method to call the constructor of a parent class (see "More Examples" below).


2 Answers

in this case

export class Component1 {

      constructor ( 
        private _commonService : CommonService, 
        private _commonServiceIndipendent:commonServiceIndipendent) {


       }

is similar to this

export class Component1 {

      private _commonService : CommonService;
      private _commonServiceIndipendent:commonServiceIndipendent;

      constructor ( 
        _commonService : CommonService, 
        _commonServiceIndipendent:commonServiceIndipendent) {

        this._commonService = _commonService; 
        this._commonServiceIndipendent = _commonServiceIndipendent;

       }

if you do not use in the constructor protected, private, or public, for example, DI, the range of the variable _commonService is the scope of the constructor { } you could not use from another function.

for example:

export class Component1 {

      constructor ( 
        _commonService : CommonService, 
        _commonServiceIndipendent:commonServiceIndipendent) {

          _commonService .... Work
       }

       foo(){

        _commonService ..... Cannot find name '_commonService'.
        this._commonService ..... Property '_commonService' does not exist on type 'yourClass'.  

       }

If you not assign it to another variable that has the scope of the class,so you no could refer to this variable, with this keyword.


export class Component1 {

  name:string; //why here?
  age:number; //why here?

//can't i add to constructor? if so how?

in typescript without Angular2, you can do this with nothing more:

constructor (name:string, age:number) {}

but in typescript with Angular2, Angular2 is responsible, most of the time, to make use of DI for exaple here:

constructor (private _commonServiceIndipendent:commonServiceIndipendent){}

you use for that providers:[commonServiceIndipendent].


Angular2: Inject a non @Injectable class

How to use Dependency Injection (DI) correctly in Angular2?

like image 195
Angel Angel Avatar answered Oct 05 '22 00:10

Angel Angel


If you delcare a field outside of the constructor it's available for tools that do static analysis, like a linter or autocompletion.

If you add fields in the constructor, such tools would need to analyze the code flow (there could be if, for, ...) in the constructor and it could depend on constructor parameters if fields are actually created or not. This makes it quite difficult and is usually not supported.

Declaring the fields outside the constructor is for a more static approach like in compiled languages. Creating them in the constructor is a dynamic approach usually not available in compiled languages.

If it's only for initializing the fields with literal values it's also more concise. You often might not even need a constructor at all.

class MyClass {
   startValue:number = 1;
}

There is also another way using a constructor

class MyClass {
  constructor(private someField:string) {}
}

which also creates a private field (could also be public). This way also makes the field known for static analysis, because the field is created unconditionally (not dependent on values only known at runtime)

like image 32
Günter Zöchbauer Avatar answered Oct 05 '22 01:10

Günter Zöchbauer