0% found this document useful (0 votes)
80 views16 pages

Const Robot

The document discusses several JavaScript concepts including: 1. Using the this keyword in methods to access the object's properties. 2. Defining getter and setter methods to control access and updating of private properties. Getters can perform actions and return different values than the stored property. 3. Creating factory functions that take parameters and return customized object instances. This allows generating multiple similar objects more easily. 4. Using property value shorthand and destructuring assignment to simplify object property assignments when the key and variable names are the same.

Uploaded by

Bhargavi Patil
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
80 views16 pages

Const Robot

The document discusses several JavaScript concepts including: 1. Using the this keyword in methods to access the object's properties. 2. Defining getter and setter methods to control access and updating of private properties. Getters can perform actions and return different values than the stored property. 3. Creating factory functions that take parameters and return customized object instances. This allows generating multiple similar objects more easily. 4. Using property value shorthand and destructuring assignment to simplify object property assignments when the key and variable names are the same.

Uploaded by

Bhargavi Patil
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

 how to use the this keyword.

 conveying privacy in JavaScript methods.


 defining getters and setters in objects.
 creating factory functions.
 using destructuring techniques.

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());

Arrow Functions and this const robot = {


  energyLevel: 100,
const goat = {
  checkEnergy() {
dietType: 'herbivore',
makeSound() {     console.log(`Energy is currently 
console.log('baaa'); at ${this.energyLevel}%.`)
},   }
diet: () => { }
console.log(this.dietType);
}
}; robot.checkEnergy();
goat.diet(); // Prints
undefined

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.

Getters  Getters can perform an action on the data


when getting a property.
Getters are methods that get and return the  Getters can return different values using
internal properties of an object. But they can conditionals.
do more than just retrieve the value of a  In a getter, we can access the properties of
property! the calling object using this.
 The functionality of our code is easier for
const person = {
_firstName: 'John', other developers to understand.
_lastName: 'Doe',
get fullName() {
if (this._firstName && const robot = {
this._lastName){   _model: '1E78V2',
return `${this._firstName} $
  _energyLevel: 100,
{this._lastName}`;
} else {   get energyLevel(){
return 'Missing a first name or     if(typeof this._energyLevel === '
a last name.';
} number') {
}       return 'My current energy level 
}
// To call the getter method: is ' + this._energyLevel
person.fullName; // 'John Doe'     } else {
      return "System malfunction: can
not retrieve energy level"
    }
  }
};

console.log(robot.energyLevel);
Setters const robot = {

Along with getter methods, we can also create   _model: '1E78V2',


setter methods which reassign values of   _energyLevel: 100,
existing properties within an object   _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 
'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently d
own.'
    }
  },
  set numOfSensors(num) {
    if (typeof num === 'number' && nu
m >= 0){
      this._numOfSensors = num;
    } else {
      console.log('Pass in a number 
that is greater than or equal to 0')
    }   
  } 
};
robot.numOfSensors = 100;
console.log(robot.numOfSensors);
A factory function is a const monsterFactory = (name, age,
function that returns an object energySource, catchPhrase) => {
and can be reused to make return {
multiple object instances. name: name,
Factory functions can also have age: age,
parameters allowing us to
energySource: energySource,
customize the object that gets
returned. scare() {
There are many different types console.log(catchPhrase);
}
of monsters and we could go }
about making each monster };
individually but we can also const robotFactory = (model, mobile) 
use a factory function to make
=> {
our lives easier. To achieve
this diabolical plan of   return {
creating multiple monsters     model : model,
objects, we can use a factory     mobile: mobile,
function that has parameters:     beep () { 
      console.log('Beep Boop'); 
    }
  };
};

const tinCan = robotFactory('P-500', 
true);
tinCan.beep();

Property Value Shorthand const monsterFactory = (name, age)


=> {
ES6 introduced some new shortcuts for return {
assigning properties to variables known as
destructing. name: name,
const monsterFactory = (name, age: age
}
age) => { };
return { function robotFactory(model, mobile){
name,
  return {
age
}     model,
};     mobile,
    beep() {
      console.log('Beep Boop');
    }
  }
}
// To check that the property value s
horthand technique worked:
const newRobot = robotFactory('P-
501', false)
console.log(newRobot.model)
console.log(newRobot.mobile)

Destructured Assignment const robot = {


  model: '1E78V2',
We often want to extract key-value pairs
from objects and save them as variables.   energyLevel: 100,
const residence =   functionality: {
vampire.residence;     beep() {
console.log(residence); //
      console.log('Beep Boop');
Prints 'Transylvania'
    },
const { residence } = vampire;     fireLaser() {
console.log(residence); //       console.log('Pew Pew');
Prints 'Transylvania'     },
  }
};
const {functionality}=robot;
functionality.beep()
 The object that a method belongs to
is called the calling object.
 The this keyword refers the calling
object and can be used to access
properties of the calling object.
 Methods do not automatically have
access to other internal properties of
the calling object.
 The value of this depends on where
the this is being accessed from.
 We cannot use arrow functions as
methods if we want to access other
internal properties.
 JavaScript objects do not have built-in
privacy, rather there are conventions
to follow to notify other developers
about the intent of the code.
 The usage of an underscore before a
property name means that the
original developer did not intend for
that property to be directly changed.
 Setters and getter methods allow for
more detailed ways of accessing and
assigning properties.
 Factory functions allow us to create
object instances quickly and
repeatedly.
 There are different ways to use object
destructuring: one way is the
property value shorthand and
another is destructured assignment.
 As with any concept, it is a good skill
to learn how to use the
documentation with objects!

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;
}
}

An instance is an object that class Surgeon {


contains the property names and   constructor(name, department) {
methods of a class, but with unique
    this.name = name;
property values
class Dog {     this.department = department;
constructor(name) {   }
this.name = name; }
this.behavior = 0; const surgeonCurry=new Surgeon('C
}
urry','Cardiovascular');
}
const halley = new const surgeonDurant=new Surgeon('
Dog('Halley'); // Create new Dog Durant','Orthopedics');
instanceconsole.log(halley.name); /
/ Log the name value saved to
halley// Output: 'Halley'

Class method and getter syntax is class Surgeon {


the same as it is for objects   constructor(name, department) {
except you can not include commas
    this._name = name;
between methods.
    this._department = department
;
    this._remainingVacationDays = 
20;
  }
  
  get name() {
    return this._name;
  }
  
  get department() {
    return this._department;
  }
  
  get remainingVacationDays() {
    return this._remainingVacatio
nDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -
= daysOff;
  }
}
const surgeonCurry = new Surgeon(
'Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon
('Durant', 'Orthopedics');
console.log(surgeonCurry.name);
surgeonCurry.takeVacationDays(3);
console.log(surgeonCurry.remainin
gVacationDays);

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.

Ecma International, the organization responsible for standardizing JavaScript,


released a new version of it in 2015, called ECMAScript2015, commonly referred to
as ES6. Note, the 6 refers to the version of JavaScript and is not related to the year it
was released (the previous version was ES5).

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}.`;

caniuse.com I Because companies add support for


ES6 features gradually, it’s important
Since Ecma’s release of ECMAScript2015 for you to know how to look up
(ES6), software companies have slowly browser support on a feature-by-
added support for ES6 features and syntax. feature basis. The website caniuse.com
While most new browser versions support is the best resource for finding browser
the majority of the ES6 library, there are compatibility information.
still a couple sources of compatibility
issues: In caniuse, you can enter an ES6
feature, like let, and see the
 Some users have not updated to the latest, percentage of browsers that recognize
ES6 supported web browser version.
it. You can also see when each major
 A few ES6 features, like modules, are still
not supported by most web browsers. web browser (Chrome, Safari, Edge,
etc.) added support for the keyword.
// Set the variable below to a numbe
// Set the variable below to a nu
r
mber
let esFivePercentageSupport=98.51;
let esSixTemplateLiterals=90.74;
Three reasons for the ES5 to ES6 updates Because ES6 addressed the above
are listed below: issues, Ecma knew that adoption by
web developers would occur quickly,
 Readability and economy of code — The while web browser support lagged
new syntax is often easier to understand behind.
(more readable) and requires fewer
characters to create the same functionality
(economy of code).
To limit the impact of ES6 browser
 Addresses sources of ES5 bugs — Some
compatibility issues, Ecma made the
ES5 syntax led to common bugs. With ES6, new syntax backwards compatible,
Ecma introduced syntax that mitigates which means you can map JavaScript
some of the most common pitfalls.
 A similarity to other programming
languages — JavaScript ES6 is syntactically ES6 code to ES5.
more similar to other object-oriented
programming languages. This leads to less
The let and const keywords were
friction when experienced, non-JavaScript
developers want to learn JavaScript. introduced in ES6. Before that,
we declared all variables with
the var keyword.
Converting ES6 to ES5 gets difficult as
the code size increases,
Because ES6 is predictably
backwards compatible, a collection
of JavaScript programmers developed
a JavaScript library called Babel
that transpiles ES6 JavaScript to
ES5.
Transpilation is the process of
converting one programming language
to another.

In the terminal window type: Checkpoint 3 Passed


3.
npm install babel-cli
In the terminal, type npm run build
This installs one of the two required Babel and press enter.
packages.
You can view the ES5 code in
Checkpoint 2 Passed ./lib/main.js.
2.
You may need to refresh to see the
In the terminal window type: newly created lib directory.

npm install babel-preset-env

This installs the second of two required


Babel packages.

Browser compatibility and transpilation: If you have Node installed on your


How to setup js project that transpiles code computer, you can create a
when you run npm run build from root directory
of js project
package.json file by typing npm init
into the terminal.
Step 1: place your ES6 js file in a directory
called src. From your root dir.,the path to ES6 The terminal prompts you to fill in
file is ./src/main.js
fields for the project’s metadata
Before we install Babel, we need to setup
our project to use the node package (name, description, etc.)
manager (npm). Developers use npm to
access and manage Node packages. Node You are not required to answer the
packages are directories that contain prompts, though we recommend at
JavaScript code written by other minimum, you add your own title and
developers. You can use these packages to description. If you don’t want to fill in a
reduce duplication of work and avoid bugs. field, you can press enter. npm will
leave fill these fields with default
Before we can add Babel to our project values or leave them empty when it
directory, we need to run npm init. The creates the package.json file.
npm init command creates a
package.json file in the root directory. After you run npm init your directory
structure will contain the following
A package.json file contains information files and folders:
about the current JavaScript project. Some
of this information includes: project
|_ src
 Metadata — This includes a project title, |___ main.js
description, authors, and more. |_ package.json
 A list of node packages required for the
project — If another developer wants to npm adds the package.json file to the
run your project, npm looks inside
package.json and downloads the packages
same level as the src directory.
in this list.
 Key-value pairs for command line scripts —
You can use npm to run these shorthand
scripts to perform some process. In a later
exercise, we will add a script that runs
Babel and transpiles ES6 to ES5.

Install node package: The -D flag instructs npm to add each


We use the npm install command to package to a property called
install new Node packages locally.devDependencies in package.json.
The install command creates a Once the project’s dependencies are
folder called node_modules and listed in devDependencies, other
copies the package files to it. The
developers can run your project
install command also installs all without installing each package
of the dependencies for the given
separately. Instead, they can simply
package.
run npm install — it instructs npm to
To insstall babel, npm install 2 look inside package.json and download
package, babel-cli and babel- all of the packages listed in
preset-env devDependencies.
$ npm install babel-cli -D
$ npm install babel-preset-env -D Once you npm install packages, you
can find the Babel packages and all
The babel-cli package includes their dependencies in the
command line Babel tools, and the node_modules folder
babel-preset-env package has the
code that maps any JavaScript
feature, ES6 and above (ES6+), to project
ES5. |_ node_modules
|___ .bin
|___ ...
|_ src
|___ main.js
|_ package.json

The ... in the file structure above is a


placeholder for 100+ packages that
npm installed.

.babelrc Your project directory contains the


following folders and files:
Now that you’ve downloaded the Babel
packages, you need to specify the version project
of the source JavaScript code. |_ node_modules
|___ .bin
You can specify the initial JavaScript |___ ...
version inside of a file named .babelrc. In |_ src
your root directory, you can run touch |___ main.js
.babelrc to create this file. |_ .babelrc
|_ package.json

Inside .babelrc you need to define the


preset for your source JavaScript file.
The preset specifies the version of your
initial JavaScript file.

Usually, you want to transpile


JavaScript code from versions ES6 and
later (ES6+) to ES5. From this point on,
we will refer to our source code as
ES6+, because Ecma introduces new
syntax with each new version of
JavaScript.

To specify that we are transpiling code


from an ES6+ source, we have to add
the following JavaScript object into
.babelrc:

{
"presets": ["env"]
}

When you run Babel, it looks in


.babelrc to determine the version of
the initial JavaScript file. In this case,
["env"] instructs Babel to transpile
any code from versions ES6 and later.

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:

 find, fix, and debug code more easily;


 reuse and recycle defined logic in different parts of our application;
 keep information private and protected from other modules;
 and, importantly, prevent pollution of the global namespace and potential naming collisions,
by cautiously selecting variables and behavior we load into a program.

You might also like