Java到JavaScript的转换
我曾多次尝试在JavaScript中理解OOP,但都没有成功 到目前为止,我读到的所有文章都非常混乱,没有用JS简洁地解释OOP 作为理解JavaScript中OOP的最后一次尝试,有人能将以下代码翻译成JS吗Java到JavaScript的转换,javascript,oop,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(Strin
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;
}
}
内干管()
输出:
My name is John Doe and I have 25 years old.
你能把它转换成JavaScript吗
另一个问题:我们可以在JavaScript中使用polimorphism吗?因为JavaScript是基于原型的,所以没有类这样的东西。您可以使用构造函数(函数)创建自定义数据类型,并通过原型提供继承
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.");
关于多态性,如果您询问的是方法重载,则没有这类问题,但是,由于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", "!");
另请看:
正如您所见,我将尝试转换上述代码,但没有成功。嘿,伙计,这是一种脚本语言。你不能在家里做这样的事javascript@AmanChhabra:好的,但至少是同等的。甚至想到JS=Java OOP始终是OOP,我认为如果您在尝试解决方案时添加指向或类似的链接,您可能会在此处获得更多响应/解决方案。@AmanChhabra,是的,您可以,展示了许多处理javascript继承的方法。谢谢(粗体)。你回答了我的问题。我不能给出+1,因为这需要15个声誉阅读本文以更详细地了解原型继承的工作原理:
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", "!");