Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript prototype propertie hookup

Tags:

javascript

var People = function()
{
    this.FirstName = "John";
    this.LastName = "Doer";
}

var Employee = function(o)
{
    this.DateHired = "June 30";
    this.prototype = o;
}

var obj = new People();
var employee1 = new Employee(obj);
print(employee1.DateHired);
print(employee1.FirstName);

Output: June 30

I expected the output should be: June 30 Jonh

but it is not what I expected. So could someone explain me what is wrong with the above code?

like image 588
hungvn Avatar asked Dec 24 '22 22:12

hungvn


1 Answers

You've set a property called prototype on the instance created by new Employee, which doesn't do anything to hook up a prototype chain. The prototype property goes on the function Employee. That property is then used to set the [[Prototype]] internal property of objects created via new Employee.

So assuming you want Employee to be a subclass of People, you'd do it like this:

// The singular is "Person", so I'll use that instead of People
var Person = function() {
  this.FirstName = "John";
  this.LastName = "Doer";
};

var Employee = function() {
  // Give `Person` a chance to do its initialization of the instance
  Person.call(this/*, possible, arguments, here*/);

  // Now carry on with the `Employee` initialization
  this.DateHired = "June 30";
};

// Make Employee a subclass of Person by
// 1. Giving `Employee.prototype` a new object whose [[Prototype]] is
//    `Person.prototype`
// 2. Ensuring that `Employee.prototype`'s `constructor` property points
//    back to Employee.
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

// Usage
var employee1 = new Employee();
console.log(employee1.DateHired);
console.log(employee1.FirstName);

However, here at the end of 2016, we don't need to play those games anymore: We can use the class syntax of ES2015 (transpiling if we need to deploy the code to older browsers), which handles the plumbing for us:

class Person {
  constructor() {
    this.FirstName = "John";
    this.LastName = "Doer";
  }
}

class Employee extends Person {
  constructor() {
    // Give `Person` its chance to initialize the instance
    super();
    // Now carry on with the `Employee` initialization
    this.DateHired = "June 30";
  }
}

// Usage
const employee1 = new Employee();
console.log(employee1.DateHired);
console.log(employee1.FirstName);
like image 104
T.J. Crowder Avatar answered Dec 26 '22 11:12

T.J. Crowder