Tuesday, December 31, 2019

Javascript Classes Syntax, the differences from Prototype



A constructor function is initialized with a number of parameters, which would be assigned as properties of this, referring to the function itself. The first letter of the identifier would be capitalized by convention.

// Initializing a class definition
class Hero {
    constructor(name, level) {
        this.name = name;
        this.level = level;
    }
}

With classes this syntax is simplified, and the method can be added directly to the class. Using the method definition shorthand introduced in ES6, defining a method is an even more concise process.

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

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


References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
https://www.digitalocean.com/community/tutorials/understanding-classes-in-javascript

No comments:

Post a Comment