HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
<title>Functions : Object Methods</title>
</head>
<body>
<!--
Object method : is a property containing a function definition/declaration.
When "this" keyword is used in an object method, it refers to the object.
-->
<h1>Demo: JavaScript Functions</h1>
<div>
<h2>Object Methods : Function within a object</h2>
<p id="para1"></p>
<p id="para2"></p>
</div>
<div>
<h2>Object Method with "this" keyword </h2>
<p id="para3"></p>
</div>
<!-- JavaScript code Starts here -->
<script>
/************************************************/
// Object Methods : Function within a object
// Example to square or cube an integer through Object methods
//
const performMath = {
Gravity: 9.81,
sqNum(int) { // sqNum: function (int) {return int ** 2; },
return int ** 2;
},
cuNum(int) { // cuNum: function (int) {return int ** 3; }
return int ** 3;
}
}
document.getElementById('para1').innerHTML =
`Square of 9 is ${performMath.sqNum(9)}`;
document.getElementById('para2').innerHTML =
`Cube of 10 is ${performMath.cuNum(10)}`;
/************************************************/
// Object Method with "this" keyword
// Example : To generate a full name using fname & lname
//
let userDetails = {
fname: "Nelson",
lname: "Mandela",
fullName: function () {
return(`${this.fname} ${this.lname}`)
} // use of "this" keyword
};
let returnVal = userDetails.fullName();
document.getElementById('para3').innerHTML =
`Full Name is ${returnVal}`;
</script>
<!-- JavaScript code Ends here -->
</body>
</html>