First I will be explaining the answers for the questions in the 2nd lab sheet in detail and the screenshots of the working code will be shown at the end of each question.
1)
//write a function as a variable that prints "Hello World" to console and another function which //accepts that variable.
var printHello = function () {
console.log("Hello World");
}
printHello(); //calling function
// The argument passed to the second function should be executed as a function inside the body.
function getInstance (hello) {
hello();
}
//Call the second function passing the first function as the argument.
getInstance(printHello);
Okay now we are done with the first question!!! 😄😄 Moving on to the 2nd question.
2)
Use curly brackets to create JSON like JavaScript object and add properties and functions
to the object.
3 )
- Declare a global variable named vehicleName in the window object
window.vehicleName = "Toyota";
- Declare a method named printVehicleName to print out the vehicle name
function printvehicleName() {
console.log("Vehicle Name = " + this.vehicleName);
}
- Declare an object named Vehicle(using object literal notation) which have a variable called vehicleName and declare a function named getVehicleName and assign it with the printVehicleName
var Vehicle = {
vehicleName:"Nissan", amount:100, id:001, getVehicleName:printvehicleName //.bind(window)
};
- Execute the printVehicleName function and the getVehicleName functions to see the results
printVehicleName();
Vehicle.getVehicleName();
Correct the getVehicleName to print out the global variable vehicleName using the this keyword.
function printVehicleName() {
console.log(this); // this prints the global vehicle name 'Toyota'
console.log("Vehicle Name = " + this.vehicleName); // prints 'Nissan'
}
4)
Create a separate function using JavaScript closure which accepts the tax percentage and
returns a function which accepts the amount and returns the amount after adding tax
percentage. Try adding tax percentage to ‘this’ object and check if it works.