Yes, but not fully OOP. It's prototype based (or object-based), that means the inheritance is based on a process of cloning of objects (or prototypes). The property "prototype" is indeed the keyword used to add new properties and new methods to an object. A prototype based language is only a sub-set of what OOP is, as we will see.
In Javascript there isn't even the concept of class, the objects are created with a function declaration, that in this case act as a constructor function:
function Student(name) { this.studentName = name; this.whoAmI = function() { alert("You are " + studentName); } } var student1 = new Student('Martin'); student1.whoAmI();
The inheritance is achieved with the prototype keyword:
function Student(name) { this.studentName = name; this.whoAmI = function() { alert("You are " + this.studentName); } this.setName = function(name) { this.studentName = name; } } function UniversityStudent(spec) { this.specialization = spec; this.showSpecialization = function() { alert("You are studying " + this.specialization); } } UniversityStudent.prototype = new Student(); var uniStudent = new UniversityStudent('Electronics'); uniStudent.setName('Martin'); uniStudent.whoAmI(); uniStudent.showSpecialization();
Apparently we can do eveything we can do in a full-fledged OOP language. But there are some valid reasons to consider Javascript not fully OOP:
1) First of all you can decide to avoide objects.
2) You break OOP every time you use the keyword prototype.
For example, in JS you can have both private or public member values:
function Student(name) { var studentName = name; // This is private this.surname; // This is public (property) }
Now, when we add a function with prototype, we can't modify a private variable:
Student.prototype.newMethod() { alert(this.surname); // That would work alert(studentName); // That breaks! }
This force to use more public values (properties) and violate encapsulation.
3) Whenever you inherit you have to use the keyword "prototype", so you break OOP again.
Suppose you want to rewrite the previous UniversityStudent object, in order to set the name. You can't expect to find the same name set, when you call the function whoAmI() from the parent.
function UniversityStudent(name, spec) { this.specialization = spec; this.studentName = name; this.showSpecialization = function() { alert("You are studing " + this.specialization); } } UniversityStudent.prototype = new Student(); var uniStudent = new UniversityStudent('Martin', 'Electronics'); uniStudent.whoAmI(); // The name will be undefined here uniStudent.showSpecialization();
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.