Latest Post

Monday, 26 December 2016

5 Best Ways to Define a JavaScript Function

JavaScript is a very flexible object-oriented language.There is various way to define a function. Following are the few example :-

1: Object Constructor Based
var employee = new Object();

    employee.name = "alok singh",
    employee.age = 30,
    employee.address = "Delhi India",
    employee.getDetails = function() {
        return this.name + " " + this.age + " " + this.address;
    };

2: Literal constructor Based:- Literals are shorter way to define objects in JavaScript.
var employee = {
    name: "alok singh",
    age: 30,
    address: "Delhi India",
    getDetails: function() {
        return this.name + " " + this.age + " " + this.address;
    }
}
3: Function Based
function Employee(name, age, address){
   this.name = name,
    this.age = age,
    this.address = address,
    getDetails = function() {
        return this.name + " " + this.age + " " + this.address;
    };
}
4: Protoype Based
function Employee(){};

Employee.prototype.name = "alok singh";
Employee.prototype.age = 30;
Employee.prototype.address = "Delhi India";
5: Function and Prototype Based
function Employee(name, age, address){
  this.name = name,
    this.age = age,
    this.address = address,
}
Employee.prototype.getDetails = function() {
        return this.name + " " + this.age + " " + this.address;
    };
6: Singleton Based:- You can use a function to define a singleton object.
Here's the syntax:
var Device = new function() {
    this.name = "Apple";
    this.model = "i-phone 6";
    this.getInfo = function() {
        return this.name + ' ' + this.model + ' device';
    }
};
console.log(Device);
Object {name: "Apple", model: "i-phone 6"}

Government Jobs