Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Object prototype in Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 189
    Comment on it

    Every javascript object has a prototype by default. And the prototypes is also an objects.
    All objects in JavaScript inherit methods and properties from  their prototype  and we can override it, but we can not override an Object with a null prototype, i.e. Object.create(null)).

    Lets create a prototype:

    function Employee(first, last, age, dept) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.dept_name = dept;
    }

     

    New keyword is used to create an object using prototype:

    var emp1 = new Employee("john", "doe", 35, "Accounts")
    var emp2 = new Employee("tom", "paul", 40, "Sales")

    Now add a new property to this object

    emp1.salary = 50000

     

    This property(salary) is added to the object emp1 only not to the emp2 or any other object. But you can not add a property like this to a prototype

    Employee.salary = 500000 // error

     

    Add method to a prototype

    function Employee(first, last, age, dept) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.dept_name = dept;
        this.fullname= function (){return this.firstName + "" + "lastName";};
    }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: