I've done many attempts to understand OOP in JavaScript without success.
All articles I've read so far are very confuse and not explain succintly OOP in JS
As a last attempt to understand OOP in JavaScript, can someone translate to JS the following code, pleas?
public class Base
{
public String firstName; // public scope to simplify
public String lastName; // the same as above
Base(String firstName, String lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
}
public class Derived extends Base
{
public int age; // public scope to simplify
Derived(String firstName, String lastName, int age)
{
super(firstName, lastName);
this.age=age;
}
}
Inside main()
Derived person = new Derived("John", "Doe", 25);
System.out.println("My name is " + person.firstName + " " + person.lastName + " and I have " + person.age + " years old.");
Output:
My name is John Doe and I have 25 years old.
Can you please convert this to JavaScript?
Another question: Can we have polimorphism in JavaScript?
Since, JavaScript is prototype based, there's no such thing as Class. You can use Constructors (functions) to create custom data types and provide inheritance by prototype.
function Base (firstName, lastName) {
// same as public in Java
this.firstName = firstName;
this.lastName = lastName;
}
function Derived (firstName, lastName, age) {
// same as calling super class in Java, and you should explicitly bind this
Base.apply(this, arguments);
this.age = age;
}
// same as extends in Java, you just override Derived.prototype with super class prototype and you should explicitly set constructor if you want later check instanceof.
Derived.prototype = Object.create(Base.prototype, {
// if you omit this line than instanceof Derived would be false, since instanceof check by prototype chain constructors.
constructor: {
value: Derived
}
});
var person = new Derived("John", "Doe", 25);
console.log(person instanceof Derived); // true
console.log(person instanceof Base); // true
console.log("My name is " + person.firstName + " " + person.lastName + " and I have " + person.age + " years old.");
Demo
About polymorphism, if you are asking about method overloading there's no such thing, but, since javascript is weakly typed dynamic language you can achieve same result with checking arguments length and typeof of that arguments. I believe that other concepts of polymorphism working same as in Java.
Simple e.g:
function bar(a, b) {
if (arguments.length === 2) {
var isInts = [].every.call(arguments, function(val) {
return !isNaN(val);
});
if (isInts) {
console.log(a + b);
}
} else if (arguments.length > 2) {
console.log([].join.call(arguments, ""));
}
}
bar(2, 5);
bar("Hello", ", ", "world", "!");
Demo
Also look at:
A re-introduction to JavaScript (JS Tutorial)
Introduction to Object-Oriented JavaScript MDN
Inheritance and the prototype chain MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With