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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3224159
  • 55
  • 1
  • 2
  • I'll try to convert the code above without success as you may see. – user3224159 Jan 22 '14 at 15:52
  • 1
    hey man, its a scripting language. you CANNOT do anything like this in javascript – Aman Chhabra Jan 22 '14 at 15:53
  • @AmanChhabra: Ok, but at least something equivalent. Even thought JS !=Java OOP is always OOP, I think – user3224159 Jan 22 '14 at 15:53
  • 1
    If you add a link to a [jsfiddle](http://jsfiddle.net/) or similar with your attempt at a solution you may get more responses/solutions here. – cazzer Jan 22 '14 at 15:59
  • @AmanChhabra, yes you can, [this question's answers](http://stackoverflow.com/questions/597769/how-do-i-create-an-abstract-base-class-in-javascript) shows many ways of dealing with inheritance in javascript. – Patrick Evans Jan 22 '14 at 16:01
  • @user3224159 as you said you have read a lot on this topic. But maybe you haven't come across this playground yet to explore JS OO thinking http://www.objectplayground.com – Stefan Jan 22 '14 at 16:05
  • @user3224159 yes inheritance is possible in javascript. I have added a snippet for the same in my answer – Aman Chhabra Jan 22 '14 at 16:08
  • I know this wasn't the question, hence me not putting this as the answer, but here is a [jsFiddle](http://jsfiddle.net/kLLJU/) showing how easy it is done using TypeScript, which compiles to JavaScript. I've commented out the original code I wrote in TS and left the compiled javascript in the fiddle. You can play around with TypeScript [here](http://www.typescriptlang.org/Playground/) – Tom Jan 22 '14 at 16:15

1 Answers1

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

Givi
  • 1,674
  • 2
  • 20
  • 35
  • 1
    THANK YOU (in bold letters). You ansewr my question. I can´t give +1 because SO requires 15 reputation – user3224159 Jan 22 '14 at 16:03
  • read this to understand how prototype inheritance works in more detail: http://dmitrysoshnikov.com/ecmascript/javascript-the-core/ – Kiran Jan 22 '14 at 16:05