3

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?

8
  • I'll try to convert the code above without success as you may see. Commented Jan 22, 2014 at 15:52
  • 1
    hey man, its a scripting language. you CANNOT do anything like this in javascript Commented Jan 22, 2014 at 15:53
  • @AmanChhabra: Ok, but at least something equivalent. Even thought JS !=Java OOP is always OOP, I think Commented Jan 22, 2014 at 15:53
  • 1
    If you add a link to a jsfiddle or similar with your attempt at a solution you may get more responses/solutions here. Commented Jan 22, 2014 at 15:59
  • @AmanChhabra, yes you can, this question's answers shows many ways of dealing with inheritance in javascript. Commented Jan 22, 2014 at 16:01

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

THANK YOU (in bold letters). You ansewr my question. I can´t give +1 because SO requires 15 reputation
read this to understand how prototype inheritance works in more detail: dmitrysoshnikov.com/ecmascript/javascript-the-core

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.