Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we don't use keyword 'function' in Angular components?

Tags:

angular

Inside the ts file,

export class ComponentName{
   methodName (para1,para2) {
     //code here
   }
}

this is considered correct but when I add the keyword function to the method, the code doesn't compile and give errors saying it only expects methods, accessors, constructors and properties.

like image 634
Ravy Avatar asked Jun 10 '17 18:06

Ravy


2 Answers

I think you are having problems understanding ECMAScript 6. Angular uses TypeScript, which is based on ECMAScript 6.

Traditional JavaScript uses functions and prototype-based inheritance to build up reusable components, but this may feel a bit awkward to programmers more comfortable with an "object-oriented approach", where classes inherit functionality and objects are built from these classes. Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers will be able to build their applications using this object-oriented class-based approach. In TypeScript, we allow developers to use these techniques now, and compile them down to JavaScript that works across all major browsers and platforms, without having to wait for the next version of JavaScript.

...

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. We declare a new class Greeter. This class has three members: a property called greeting, a constructor, and a method greet.

[Source]

like image 69
virsha Avatar answered Oct 13 '22 15:10

virsha


As mention @virsha, it's not about Angular it's about ECMAScript 6 method definitions.

Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name.

const obj = {
  foo() {
    return 'bar';
  }
};

console.log(obj.foo());
// expected output: "bar"

The shorthand syntax is similar to the getter and setter syntax introduced in ES5.

Given the following code:

const obj = {
  foo: function() {
    // ...
  },
  bar: function() {
    // ...
  }
}

You are now able to shorten this to:

const obj = {
  foo() {
    // ...
  },
  bar() {
    // ...
  }
}

In Typescript documentation this refers to Class methods.

A function property on a class is called a method. Methods can use all the same type annotations as functions and constructors:

class Point {
  x = 10;
  y = 10;

  scale(n: number): void {
    this.x *= n;
    this.y *= n;
  }
}

Other than the standard type annotations, TypeScript doesn’t add anything else new to methods.

like image 34
israteneda Avatar answered Oct 13 '22 15:10

israteneda