0

I am trying to learn inheritance in JavaScript using prototype keyword.

I came a code across a web-site which explained me classical inheritance in JavaScript. I am using Mozilla Rhino for command-line javaScript

This is my code

    var fn55 = function(){

    var Employee = function(name){

        var name = name;

        this.getName = function(){
            return name;
        };

        this.setName = function(empName){
            name = empName;
        };  
    };

    var ContractEmp = function(name,sal){
        var salary = sal;

        this.getSalary = function(){
            return salary;
        }
        //calling super constructor
        Employee.apply(this,[name]);            
    };
    ContractEmp.prototype = new Employee();
    ContractEmp.prototype.constructor = ContractEmp;


    var emp1 = new ContractEmp("Jack",3000);
    var emp2 = new ContractEmp("John",4000);
    print(emp1.getName());
    print(emp2.getName());
    print(emp1.getName());

    Employee.prototype.getInfo = function(){
        return "Emp Name \""+this.getName()+"\" Salary "+this.getSalary();
    }

    print(emp1.getInfo());
};

fn55();

the output is

Jack
John
Jack
Emp Name "Jack" Salary 3000

Now if I comment a line in my code

//ContractEmp.prototype.constructor = ContractEmp;

the output remains as it is.

So my question is, whats the purpose of this re-assigning the constructor

Rahul Shivsharan
  • 2,481
  • 7
  • 40
  • 59
  • I believe this is due to some ancient IE behavior, never reassigned the constructor and never bit me :-) – mfeineis Jun 01 '15 at 07:26
  • It is not necessary to assign a constructor to a prototype object, but it can be helpful under circumstances. Then `myObject.constructor` can be used to access an object's constructor at runtime. – GOTO 0 Jun 01 '15 at 07:34

1 Answers1

0

So my question is, whats the purpose of this re-assigning the constructor

The only purpose is to reset constructor to its original value.

See also What it the significance of the Javascript constructor property?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143