JSFiddle - React, Tailwind, and code Playground
JavaScript
// http://daniel.steigerwald.cz (MIT Licensed)
// pomocná funkce pro dědění
var extends = function(child, parent) {
// F je pomocný dočasný konstruktor
var F = function() {};
F.prototype = parent.prototype;
child.prototype = new F();
// konvence pro volání přepsaných metod
child._superClass = parent.prototype;
// dobrým zvykem je, aby instance odkazovala na svůj konstruktor
child.prototype.constructor = child;
};
// třída Person
var Person = function(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
// třída Employee
var Employee = function(name, salary) {
// zavoláme bázový konstruktor
Person.call(this, name);
this.salary = salary;
};
// podědíme
extends(Employee, Person);
Employee.prototype.getSalary = function() {
return this.salary;
};
// přepisujeme metodu z třídy Person
Employee.prototype.getName = function() {
// voláme přepsanou metodu
var name = Employee._superClass.getName.call(this);
return name + ' (zaměstnanec)';
};
// vytvoříme instanci
var joe = new Employee('Joe', 1000);
// zkusmo přidáme metodu bázové třídě Person
Person.prototype.setName = function(name) {
this.name = name;
};
// a teď tuto metodu vyzkoušíme na instanci Employee
joe.setName('Pepa');
// všechny tyto testy musí projít
alert([
joe.getName() == 'Pepa (zaměstnanec)',
joe.getSalary() == 1000,
joe instanceof Person,
joe instanceof Employee,
typeof Employee == 'function',
typeof joe == 'object',
joe.constructor == Employee,
Employee._superClass == Person.prototype
]);