Saturday, February 18, 2017

JavaScript Classes and Prototypes

This is a tutorial on the 1st lab session of Application Frameworks conducted at SLIIT for the 3rd year 1st semester batch .
Basically in this tutorial we will learn about JavaScript functions, variables, statements etc.

 First question is  to write a JavaScript function to update a text typed by a user in a text box to a div in real time. 




















Note that i have used "onKeyUp" as a event for the textbox. The onKeyUp event executes the JavaScript function when the user releases a key on the keyboard.

Second question is to create a JavaScript class called Vehicle and Car. Car class should extend from Vehicle class. Vehicle class should have a method to set and price of the Vehicle.

First of all I created a html file and a JavaScript file and linked the js file to the the html file as shown below.















In JavaScript we don't define methods inside the constructor function instead we add functions to the prototype chain.

function Vehicle () {
   
             this.amount = 1000;
                                  
                                 }

Vehicle.prototype.setAmount = function (amount) {
             
               this.amount = amount ; 
  
                                }

We can use the Object.create() approach to extend Car class from Vehicle Class. (Inheritance)

Car.prototype = Object.create(Vehicle.prototype);

Car.prototype.constructor = Car; //This is just to make sure that the correct constructor is being called.
Next we should create a object from Car class
var car = new Car();

Notice that the amount is printing as undefined and when you enter OK the new set amount is displayed as 10000.




--- Ashen Jayasinghe ---

No comments:

Post a Comment