Java到JavaScript的转换

use*_*159 3 javascript oop

我已经做了很多尝试在JavaScript中理解OOP但没有成功.

到目前为止我读过的所有文章都非常混乱,而且在JS中没有简单地解释OOP

作为在JavaScript中理解OOP的最后一次尝试,有人可以将以下代码转换为JS,请求?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

里面主()

    Derived person = new Derived("John", "Doe", 25);

    System.out.println("My name is " + person.firstName + " " + person.lastName + " and I have " + person.age + " years old.");
Run Code Online (Sandbox Code Playgroud)

输出:

My name is John Doe and I have 25 years old.
Run Code Online (Sandbox Code Playgroud)

你能把它转换成JavaScript吗?

另一个问题:我们可以在JavaScript中使用polimorphism吗?

Giv*_*ivi 5

因为,JavaScript是基于原型的,所以没有Class这样的东西.您可以使用构造函数(函数)来创建自定义数据类型并按原型提供继承.

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.");
Run Code Online (Sandbox Code Playgroud)

演示


关于多态,如果你问的是方法重载没有这样的东西,但是,由于javascript是弱类型的动态语言,你可以通过检查参数的长度和类型来获得相同的结果.我相信多态的其他概念与Java中的相同.
简单例如:

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", "!");
Run Code Online (Sandbox Code Playgroud)

演示


另请参阅:
重新介绍JavaScript(JS教程)
面向对象的JavaScript简介MDN
继承和原型链MDN