Even more compact than this but exactly equivalent and a little bit of mind twister....
Note that the "super" function name is specified only once in the constructor function. And if the order of parameters of "super" is consistent and it ignores the extra params the
arguments.callee.prototype.__proto__.constructor.call(this, name, salary);
in Executive can even be replaced by:
arguments.callee.prototype.__proto__.constructor.apply(this, arguments);
making it completely boiler plate.
This will allow private and read-only properties also. Can anyone show how?
Code:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
function Employee(name, salary) {
// One time initialization of instance methods
if (arguments.callee.prototype.__proto__ === Object.prototype) {
arguments.callee.prototype.__proto__ = Person.prototype;
arguments.callee.prototype.getSalary = function() {
return this.salary;
}
}
arguments.callee.prototype.__proto__.constructor.call(this, name);
this.salary = salary;
}
function Executive(name, salary, bonus) {
// One time initialization of instance methods
if (arguments.callee.prototype.__proto__ === Object.prototype) {
arguments.callee.prototype.__proto__ = Employee.prototype;
arguments.callee.prototype.getBonus = function() {
return this.bonus;
}
}
arguments.callee.prototype.__proto__.constructor.call(this, name, salary);
this.bonus = bonus;
}
var hotshot = new Executive('Hotshot', 400000, 100000);
var workerbee = new Employee('Workerbee', 100000);
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
function Employee(name, salary) {
// One time initialization of instance methods
if (arguments.callee.prototype.__proto__ === Object.prototype) {
arguments.callee.prototype.__proto__ = Person.prototype;
arguments.callee.prototype.getSalary = function() {
return this.salary;
}
}
arguments.callee.prototype.__proto__.constructor.call(this, name);
this.salary = salary;
}
function Executive(name, salary, bonus) {
// One time initialization of instance methods
if (arguments.callee.prototype.__proto__ === Object.prototype) {
arguments.callee.prototype.__proto__ = Employee.prototype;
arguments.callee.prototype.getBonus = function() {
return this.bonus;
}
}
arguments.callee.prototype.__proto__.constructor.call(this, name, salary);
this.bonus = bonus;
}
var hotshot = new Executive('Hotshot', 400000, 100000);
var workerbee = new Employee('Workerbee', 100000);
hotshot instanceof Executive => true
hotshot instanceof Employee => true
hotshot instanceof Person => true
workerbee instanceof Executive => false
workerbee instanceof Employee => true
workerbee instanceof Person => true
It is my understanding that arguments.callee is going to be deprecated in ES6. No fear, it can simply be replaced by the CTOR function name.
No comments:
Post a Comment