-1

Why the following code works if I use the arrow function but gives error if used with function keyword?

export class WeatherComponent implements OnInit {
  isShowResult = false;
  result: any;
  constructor(public api: ApiService) {}
  ngOnInit(): void {}
  changeStatus() {
    this.api.modifyStatus();
  }
  getWeather(city: string) {
    this.api.getWeatherReport(city).subscribe
    (
      (data: any) => {

        this.isShowResult = true;
        this.result = data;
      },
      (error: any) => {console.log(error);},
      () => {console.log('Api call completed');}
    );
  }
}

But if I replace arrow function with function keyword it gives error as "'this' implicitly has type 'any' because it does not have a type annotation."

getWeather(city: string) {
    this.api.getWeatherReport(city).subscribe(

      function(data: any) {

        this.isShowResult = true;
        this.result = data;
      },
      (error: any) => {console.log(error);},
      () => {console.log('Weather api call completed');}
    );
  }
  • 3
    Read about `this` difference between arrow functions and functions: [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – Adrian Kokot Jul 07 '23 at 09:02

1 Answers1

-1

I will give you a simple scenario to understand this keyword how it works. In a regular function, the value of this is determined dynamically based on how the function is called. It typically refers to the object that called the function or the object to the left of the dot when the function is called as a method. Here's an example below

const person = {
  name: 'John',
  sayHello: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

person.sayHello(); // Output: Hello, my name is John.

However, in an arrow function, the current value of this is determined by the surrounding scope at the time of the function's definition. The arrow function does not have its own this value. Instead, it inherits the this value from its enclosing scope. Here's an example to illustrate this behavior


const person = {
  name: 'John',
  sayHello: () => {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

person.sayHello(); // Output: Hello, my name is undefined.

I Hope this example might clarify the problem. Happy coding.

Sadek Mehri
  • 50
  • 1
  • 5