An older way of writing object creators and adding object methods is to use function keyword:
function createStudent(firstName, lastName) {
return {
region: '',
skills: {},
name: `${firstName} ${lastName}`,
}
}
// To add a method:
createStudent.prototype.getName = function () {
// ...
}
// To create an object off of createStudent:
const myObject = createStudent('Sam', 'Barli');
Classes
The class syntax is a newer and more convenient way for us to write code that creates objects.
Let the constructor take in two arguments:
class Student {
constructor(firstName, lastName) {
// ...
}
}
Then use those two arguments to create a new property, name:
constructor(firstName, lastName) {
// The backticks treat data inside as a string unless it's between ${}, which treats data inside as JavaScript values.
this.name = `${firstName} ${lastName}`;
// Alternatively:
this.name = 'firstName ' + 'lastName';
}
By adding the property to the this object, we let all instances of the class have access to it.
To add methods to this class, simply add them directly inside it:
Each constructed object has access to the methods in the `class`:
```JS
const firstStudent = new createStudent('Samantha', 'Barli');
const secondStudent = new createStudent('Andy', 'Weiss');
firstStudent.getName(); // 'Samantha Sally'
secondStudent.getName(); // 'Andy Weiss'
delete Keyword
The delete keyword can be used to delete a property/value pair from an object.
Classes & Methods
An older way of writing object creators and adding object methods is to use
function
keyword:Classes
The
class
syntax is a newer and more convenient way for us to write code that creates objects.Let the
constructor
take in two arguments:Then use those two arguments to create a new property,
name
:By adding the property to the
this
object, we let all instances of the class have access to it.To add methods to this class, simply add them directly inside it:
To create a
newStudent
object off thisStudent
"mold" (i.e. theclass
), use thenew
keyword:// newStudent object looks like: // { name: 'Samantha Barli' }
delete
KeywordThe
delete
keyword can be used to delete a property/value pair from an object.Default parameters
A parameter can be initialized with default values if the function is called without passing in a value for it.
Example from MDN:
How to look at all the keys in an object?
Object.keys()
(Refer to the docs here)Programming tips:
CMND
+/
(orCtrl
+/
).CMND
+D
(orCtrl
+D
) to select all instances of that text. You can then edit all these instances simultaneously.To bring in the data from another file into our file:
const data = require(__filePath__);