Javascript
/
Objects
- 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 Objects Constructor
In JS {...} creates only one object With new we can create many similar objects function User(name) this.name = name A = new User("Jack")Constructors
New
Often we need to create many similar objects.
/**
* The 'new' operator allows to create many similar objects
* The regular {...} allows to create only one object
*
* Any function can be run with new
* The capital first letter is a convention
*
* Private constructor (Singleton):
* Encapsulate code that construct the object,
* without future reuse
*/
function User(name) {
this.name = name;
// this = {}; // implicit
// return this; // implicit
}
let A = new User("Jack");
let B = new User("Mike");
let C = new function(name) { // Singleton
this.name = "John";
this.isAdmin = true;
}
console.log(A.name); // Jack
console.log(B.name); // Mike
console.log(C.isAdmin); // true
Methods
We can add to this not only properties, but methods as well.
/**
* We can add methods to constructor
* For more complex syntax, we will use classes
*
* JavaScript provides constructor functions for many
* built-in language objects: like Date or Set
*/
function User(name, birthdate) {
this.name = name;
this.age = new Date().getFullYear() - new Date(birthdate).getFullYear();
this.isAdult = this.age >= 18;
this.show = () => {
console.log(this.name + ' is adult: ' + this.isAdult);
}
}
let user = new User("John", '01-01-1980');
user.show(); // John is adult: true
➥ Questions
Last update: 117 days ago