object oriented programming: …...employee.prototype = new person(); employee.prototype.constructor...
TRANSCRIPT
Phachaya ChaiwchanLecturer in Information Science
Suan Sunandha Rajabhat University
Bangkok , Thailand
OBJECT ORIENTED PROGRAMMING:
POLYMORPHISM and ABSTRACTION
IN JAVASCRIPT
POLYMORPHISM
POLYMORPHISM
EXAMPLE
POLYMORPHISM
function Person(age, weight) {
this.age = age; this.weight = weight;
this.getInfo = function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kg.";
}
}
function Employee(age, weight, high) {
this.high = high;
this.age = age;
this.weight = weight;
this.getInfo = function() {
return "I am " + this.age + " years old " +
"and weighs " + this.weight +" kg. " +
"and high " + this.high + " cm.";
}
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;// The argument, 'obj', can be of any kind
// which method, getInfo(), to be executed depend on the
object
// that 'obj' refer to.
function showInfo(obj) { document.write(obj.getInfo()
+ "<br>");
}
var person = new Person(25,60);
var employee = new Employee(42,80,170);
showInfo(person); showInfo(employee);
ABSTRACTION
ABSTRACTION
ABSTRACTION
EXAMPLE
ABSTRACTION
EXAMPLE
•
Person
First name
Last name
Skills
Job
Job
Company
Position
Salary
Zara
David
Mike
Developer
Web
Designer
•
•
ABSTRACTION
EXAMPLE
class Person {
constructor({firstName, lastName, job}) {
this.firstName = firstName;
this.lastName = lastName;
this.job = job;
this.skills = [];
Person._amount = Person._amount || 0;
Person._amount++;
}
static get amount() {
return Person._amount;
}
return Person._amount;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(fN) {
if (/[A-Za-z]\s[A-Za-z]/.test(fN)) {
[this.firstName, this.lastName] = fN.split(' ');
} else {
throw Error('Bad fullname');
}
}
learn(skill) {
this.skills.push(skill);
}
}
ABSTRACTION
EXAMPLE
class Job {
constructor(company, position, salary) {
this.company = company;
this.position = position;
this.salary = salary;
}
}
const david = new Person({
firstName: ‘David',
lastName: ‘Jone',
job: new Job('Youtube', 'developer', 200000)
});
const mike = new Person({
firstName: ‘Mike',
lastName: 'Smith',
job: new Job('ATP', ‘WebDesigner', 1000000)
});
david.fullName = ‘David Jone';
david.learn(‘MIS01');
mike.learn('programming');
david.learn(‘MIS02');
ABSTRACTION
•
•
•
•
•
Q & A