Constructor
Classes are a more advance object construct (unlike new function()).
/**
* Classes
*
* In JavaScript, a class is a special kind of function
* The constructor() method is called automatically by new
* No comma required between class methods
* Classe always use strict
*/
class User
{
constructor (name) {
this.name = name;
}
hello() {
console.log("Hi, this is " + this.name);
}
}
let a = new User("Mihai");
let b = new User("John");
a.hello(); // Hi, this is Mihai
b.hello(); // Hi, this is John
Getter
Just like literal objects, classes may include getters and setters.
/**
* Get/Set
*
* Technically, such class declaration works by creating
* getters and setters in MyClass.prototype
*/
class MyClass
{
constructor (msg) {
this.msg = msg; // invokes the setter
}
set msg(str) {
str = str.toUpperCase();
this._msg = str; // Look Here
}
get msg() {
return this._msg;
}
}
let obj = new MyClass("hello world");
try {
console.log(obj.msg + "!"); // HELLO WORLD!
console.log(obj.msg());
} catch (err) {
console.log(err.message); // obj.msg is not a function
}
Last update: 445 days ago