Javascript-OOPs(Part1)-Objects - (7)

  

👉Javascript with OOPs


New javascript specification ES6 introduced "Javascript classes" though it uses "function" internally,  previous frameworks don't allow the "class" keyword, and the below example creates a class using Javascript functions.


*Create class and object

function Customer(){ //class template

}

var cust = new Customer(); //object


*Create Method and Properties

function Customer(){ 

      this.CustomerName = "";

      this.CustomerCode = "";

      this.submit = function() {

           alert("Submit" + this.CustomerName + " " +

                      this.CustomerCode);

}

var cust = new Customer(); 

cust.CustomerName = "John";

cust.CustomerCode = "1001";

cust.Submit();


The above example defines only variables, which are not secure and not good for developing business components. To define properties in javascript, we don't have direct "getter" and "setter", we need to create functions, and rather than creating separate "getter" and "setter", for better code management we can create properties as shown below, wherein we set the value when it is provided and gets the value otherwise.


function Customer(){ 

      var _CustomerName = "";

      var _CustomerCode = "";

      this.CustomerCode = function(value) {

           if (value == undefined) {

                    return _CustomerCode;

           }

           _CustomerCode = value;

}

      this.CustomerName = function(value) {

           if (value == undefined) {

                    return _CustomerName;

           }

           if (value.Length == 0) { return; }

           _CustomerName = value;

}

      this.submit = function() {

           alert("Submit" + this.CustomerName + " " +

                      this.CustomerCode);

}

var cust = new Customer(); 

cust.CustomerName = "John";

cust.CustomerCode = "1001";

cust.Submit();


Comments

Popular posts from this blog

Javascript-OOPs(Part2)-AbstractionAndEncapsulation- (8)

Javascript-OOPs(Part4)-Polymorphism- (10)