Javascript
/
Classes
- 1 Fundamentals 11
-
Hello World S
-
Code structure S
-
Use strict S
-
Variables S
-
Data types S
-
Type conversions S
-
Maths S
-
Comparitions S
-
Conditional S
-
Loops S
-
Functions S
- 2 Testing 2
-
Mocha S
-
Nested describe S
- 3 Objects 4
-
Basics S
-
Reference S
-
Methods S
-
Constructor S
- 4 Types 5
-
Primitives S
-
Numbers S
-
Strings S
-
Arrays S
-
Json S
- 5 Classes 3
-
Constructor S
-
Binding S
-
Inheritance S
S
R
Q
Javascript Classes Constructor
In JS a class is a special kind of function Just like objects, may include getters/setters class A constructor(name) this.name = name a = new A("Jack")Constructors
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
}
➥ Questions