Const Robot
Const Robot
const robot = {
model: 'B-4MI',
mobile: true,
greetMaster() {
console.log(`I'm model ${this.model}, how may I be of service?`);
}
}
const massProdRobot = (model, mobile) => {
return {
model,
mobile,
greetMaster() {
console.log(`I'm model ${this.model}, how may I be of service?`);
}
}
}
const shinyNewRobot = massProdRobot('TrayHax', true)
const chargingStation = {
_name: 'Electrons-R-Us',
_robotCapacity: 120,
_active: true,
_chargingRooms: ['Low N Slow', 'Middle of the Road', 'In and Output']
,
set robotCapacity(newCapacity) {
if (typeof newCapacity === 'number') {
this._robotCapacity = newCapacity;
} else {
console.log(`Change ${newCapacity} to a number.`)
}
},
get robotCapacity() {
return this._robotCapacity;
}
}
This use const robot = {
model: '1E78V2',
energyLevel: 100,
provideInfo() {
return `I am ${this.model} and my
current energy level is $
{this.energyLevel}.`
}
};
console.log(robot.provideInfo());
Privacy : const robot = {
Accessing and updating properties is
fundamental in working with objects. _energyLevel: 100,
However, there are cases in which we recharge(){
don’t want other code simply
accessing and updating an object’s this._energyLevel += 30;
properties. When discussing privacy in console.log(`Recharged! Energy is
objects, we define it as the idea that
currently at ${this._energyLevel}%.`)
only certain properties should be
mutable or able to change in value. }
};
One common convention is to place an
underscore _ before the name of a robot._energyLevel='high'
property to mean that the property robot.recharge()
should not be altered.
console.log(robot.energyLevel);
Setters const robot = {
const tinCan = robotFactory('P-500',
true);
tinCan.beep();
Introduction to class:
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior ++;
}
}
const halley = new Dog('Halley');
console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console
halley.incrementBehavior(); // Add one to behavior
console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console
Constructor: class Surgeon {
JavaScript calls the constructor()
constructor(name, department) {
method every time it creates a new
instance of a class. this.name = name;
this.department = department;
class Dog { }
constructor(name) { }
this.name = name;
this.behavior = 0;
}
}
Inheritance class HospitalEmployee {
constructor(name) {
The extends keyword makes the
methods of the animal class available this._name = name;
inside the cat class. this._remainingVacationDays =
The constructor, called when you create a
20;
new Cat object, accepts two arguments,
name and usesLitter. }
The super keyword calls the constructor
of the parent class. In this case, get name() {
super(name) passes the name
argument of the Cat class to the return this._name;
constructor of the Animal class. When }
the Animal constructor runs, it sets
this._name = name; for new Cat
instances. get remainingVacationDays() {
_usesLitter is a new property that is return this._remainingVacatio
unique to the Cat class, so we set it in the nDays;
Cat constructor.
}
takeVacationDays(daysOff) {
this._remainingVacationDays -
= daysOff;
}
}
class Nurse extends HospitalEmployee nurseOlynyk.takeVacationDays(5);
{ console.log(nurseOlynyk.remaining
constructor(name, certifications) VacationDays);
{
super(name);
we will add a usesLitter getter.
this._certifications = certifica The syntax for creating getters,
tions; setters, and methods is the same
} as it is in any other class.
} class Cat extends Animal {
constructor(name, usesLitter)
{
const nurseOlynyk = new Nurse('Olyny super(name);
k', ['Trauma', 'Pediatrics']); this._usesLitter =
usesLitter;
}
static generatePassword() {
return Math.floor(Math.random()
get usesLitter() {
return this._usesLitter;
* 10000); }
} }
addCertification(newCertification
) {
this._certifications.push(new
Certification);
}
nurseOlynyk.addCertification('Gen
etics');
console.log(nurseOlynyk.certifica
tions);
You’re probably prompted to update your web browser every few months. Do
you know why? A few reasons include addressing security vulnerabilities,
adding features, and supporting new HTML, CSS, and JavaScript syntax.
Upon release, web developers quickly adopted the new ES6 syntax, as it improved
readability and efficiency. However, ES6 was not supported by most web browsers,
so developers ran into browser compatibility issues.
caniuse.com — A website that provides data on web browser compatibility for HTML, CSS,
and JavaScript features. You will learn how to use it to look up ES6 feature support.
Babel — A Javascript library that you can use to convert new, unsupported JavaScript (ES6),
into an older version (ES5) that is recognized by most modern browsers.
var pasta = "Spaghetti"; // ES5 synt
ax
const meat = "Pancetta"; // ES6 synt
ax
let sauce = "Eggs and cheese"; // ES
6 syntax
//The code includes three features o
f ES6 syntax: const, let, and ES6 st
ring interpolation.
const carbonara = `You can make carb
onara with ${pasta}, ${meat}, and a
sauce made with ${sauce}.`;
{
"presets": ["env"]
}
Build project
|_ lib
We’re ready to transpile our code! In the |___ main.js
last exercise, we wrote the following script |_ node_modules
in package.json: |___ .bin
|___ ...
"build": "babel src -d lib" |_ src
|___ main.js
Now, we need to call "build" from the |_ .babelrc
command line to transpile and write ES5 |_ package.json
code to a directory called lib.
Notice, the directory contains a new
From the command line, we type: folder named lib, with one file, called
main.js.
npm run build
The npm run build command will
The command above runs the build script transpile all JavaScript files inside of
in package.json. the src folder. This is helpful as you
build larger JavaScript projects —
Babel writes the ES5 code to a file named regardless of the number of JavaScript
main.js (it’s always the same name as the files, you only need to run one
original file), inside of a folder called lib. command (npm run build) to
The resulting directory structure is: transpile all of your code.
ES5 — The old JavaScript version that is For future reference, here is a list of
supported by all modern web browsers. the steps needed to set up a project
ES6 — The new(er) JavaScript version that for transpilation:
is not supported by all modern web Initialize your project using npm init
browsers. The syntax is more readable, and create a directory called src
similar to other programming languages, Install babel dependencies by
and addresses the source of common bugs running
in ES5. npm install babel-cli -D
caniuse.com — a website you can use to npm install babel-preset-env -D
look up HTML, CSS, and JavaScript browser
Create a .babelrc file inside your
compatibility information.
project and add the following code
Babel — A JavaScript package that
inside it:
transpiles JavaScript ES6+ code to ES5.
{
npm init — A terminal command that
"presets": ["env"]
creates a package.json file.
}
package.json — A file that contains
information about a JavaScript project. Add the following script to your
npm install — A command that
scripts object in package.json:
installs Node packages. "build": "babel src -d lib"
babel-cli — A Node package that Run npm run build whenever you
contains command line tools for Babel. want to transpile your code from
babel-preset-env — A Node package your src to lib directories.
that contains ES6+ to ES5 syntax mapping
information.
.babelrc — A file that specifies the version
of the JavaScript source code.
"build" script — A package.json script
that you use to tranpsile ES6+ code to ES5.
npm run build — A command that
runs the build script and transpiles ES6+
code to ES5.
There’s one last step before we can transpile our code. We need to specify a script in
package.json that initiates the ES6+ to ES5 transpilation.
Inside of the package.json file, there is a property named "scripts" that holds an
object for specifying command line shortcuts. It looks like this:
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
}, ...
In the code above, the "scripts" property contains an object with one property
called "test". Below the "test" property, we will add a script that runs Babel like
this:
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel src -d lib"
}
In the "scripts" object above, we add a property called "build". The property’s
value, "babel src -d lib", is a command line method that transpiles ES6+ code to
ES5. Let’s consider each argument in the method call:
babel — The Babel command call responsible for transpiling code.
src — Instructs Babel to transpile all JavaScript code inside the src directory.
-d — Instructs Babel to write the transpiled code to a directory.
lib — Babel writes the transpiled code to a directory called lib.
In the next exercise, we’ll run the babel src -d lib method to transpile our ES6+
code.
Hello Modules:
Js modules are reusable poece of code that cn be exported from one program and
imported for use in another program.
Modules are particularly useful for a number of reasons. By separating code with
similar logic into files called modules, we can: